content
stringlengths 1
103k
⌀ | path
stringlengths 8
216
| filename
stringlengths 2
179
| language
stringclasses 15
values | size_bytes
int64 2
189k
| quality_score
float64 0.5
0.95
| complexity
float64 0
1
| documentation_ratio
float64 0
1
| repository
stringclasses 5
values | stars
int64 0
1k
| created_date
stringdate 2023-07-10 19:21:08
2025-07-09 19:11:45
| license
stringclasses 4
values | is_test
bool 2
classes | file_hash
stringlengths 32
32
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
from __future__ import annotations\n\n# Use of this source code is governed by the MIT license.\n__license__ = "MIT"\n\nfrom collections import defaultdict\nimport re\nfrom types import ModuleType\nfrom typing import (\n Any,\n cast,\n Dict,\n Iterable,\n List,\n Optional,\n Pattern,\n Set,\n Tuple,\n Type,\n TYPE_CHECKING,\n)\nimport warnings\nimport sys\nfrom bs4.element import (\n AttributeDict,\n AttributeValueList,\n CharsetMetaAttributeValue,\n ContentMetaAttributeValue,\n RubyParenthesisString,\n RubyTextString,\n Stylesheet,\n Script,\n TemplateString,\n nonwhitespace_re,\n)\n\n# Exceptions were moved to their own module in 4.13. Import here for\n# backwards compatibility.\nfrom bs4.exceptions import ParserRejectedMarkup\n\nfrom bs4._typing import (\n _AttributeValues,\n _RawAttributeValue,\n)\n\nfrom bs4._warnings import XMLParsedAsHTMLWarning\n\nif TYPE_CHECKING:\n from bs4 import BeautifulSoup\n from bs4.element import (\n NavigableString,\n Tag,\n )\n from bs4._typing import (\n _AttributeValue,\n _Encoding,\n _Encodings,\n _RawOrProcessedAttributeValues,\n _RawMarkup,\n )\n\n__all__ = [\n "HTMLTreeBuilder",\n "SAXTreeBuilder",\n "TreeBuilder",\n "TreeBuilderRegistry",\n]\n\n# Some useful features for a TreeBuilder to have.\nFAST = "fast"\nPERMISSIVE = "permissive"\nSTRICT = "strict"\nXML = "xml"\nHTML = "html"\nHTML_5 = "html5"\n\n__all__ = [\n "TreeBuilderRegistry",\n "TreeBuilder",\n "HTMLTreeBuilder",\n "DetectsXMLParsedAsHTML",\n\n "ParserRejectedMarkup", # backwards compatibility only as of 4.13.0\n]\n\nclass TreeBuilderRegistry(object):\n """A way of looking up TreeBuilder subclasses by their name or by desired\n features.\n """\n\n builders_for_feature: Dict[str, List[Type[TreeBuilder]]]\n builders: List[Type[TreeBuilder]]\n\n def __init__(self) -> None:\n self.builders_for_feature = defaultdict(list)\n self.builders = []\n\n def register(self, treebuilder_class: type[TreeBuilder]) -> None:\n """Register a treebuilder based on its advertised features.\n\n :param treebuilder_class: A subclass of `TreeBuilder`. its\n `TreeBuilder.features` attribute should list its features.\n """\n for feature in treebuilder_class.features:\n self.builders_for_feature[feature].insert(0, treebuilder_class)\n self.builders.insert(0, treebuilder_class)\n\n def lookup(self, *features: str) -> Optional[Type[TreeBuilder]]:\n """Look up a TreeBuilder subclass with the desired features.\n\n :param features: A list of features to look for. If none are\n provided, the most recently registered TreeBuilder subclass\n will be used.\n :return: A TreeBuilder subclass, or None if there's no\n registered subclass with all the requested features.\n """\n if len(self.builders) == 0:\n # There are no builders at all.\n return None\n\n if len(features) == 0:\n # They didn't ask for any features. Give them the most\n # recently registered builder.\n return self.builders[0]\n\n # Go down the list of features in order, and eliminate any builders\n # that don't match every feature.\n feature_list = list(features)\n feature_list.reverse()\n candidates = None\n candidate_set = None\n while len(feature_list) > 0:\n feature = feature_list.pop()\n we_have_the_feature = self.builders_for_feature.get(feature, [])\n if len(we_have_the_feature) > 0:\n if candidates is None:\n candidates = we_have_the_feature\n candidate_set = set(candidates)\n else:\n # Eliminate any candidates that don't have this feature.\n candidate_set = candidate_set.intersection(set(we_have_the_feature))\n\n # The only valid candidates are the ones in candidate_set.\n # Go through the original list of candidates and pick the first one\n # that's in candidate_set.\n if candidate_set is None or candidates is None:\n return None\n for candidate in candidates:\n if candidate in candidate_set:\n return candidate\n return None\n\n\n#: The `BeautifulSoup` constructor will take a list of features\n#: and use it to look up `TreeBuilder` classes in this registry.\nbuilder_registry: TreeBuilderRegistry = TreeBuilderRegistry()\n\n\nclass TreeBuilder(object):\n """Turn a textual document into a Beautiful Soup object tree.\n\n This is an abstract superclass which smooths out the behavior of\n different parser libraries into a single, unified interface.\n\n :param multi_valued_attributes: If this is set to None, the\n TreeBuilder will not turn any values for attributes like\n 'class' into lists. Setting this to a dictionary will\n customize this behavior; look at :py:attr:`bs4.builder.HTMLTreeBuilder.DEFAULT_CDATA_LIST_ATTRIBUTES`\n for an example.\n\n Internally, these are called "CDATA list attributes", but that\n probably doesn't make sense to an end-user, so the argument name\n is ``multi_valued_attributes``.\n\n :param preserve_whitespace_tags: A set of tags to treat\n the way <pre> tags are treated in HTML. Tags in this set\n are immune from pretty-printing; their contents will always be\n output as-is.\n\n :param string_containers: A dictionary mapping tag names to\n the classes that should be instantiated to contain the textual\n contents of those tags. The default is to use NavigableString\n for every tag, no matter what the name. You can override the\n default by changing :py:attr:`DEFAULT_STRING_CONTAINERS`.\n\n :param store_line_numbers: If the parser keeps track of the line\n numbers and positions of the original markup, that information\n will, by default, be stored in each corresponding\n :py:class:`bs4.element.Tag` object. You can turn this off by\n passing store_line_numbers=False; then Tag.sourcepos and\n Tag.sourceline will always be None. If the parser you're using\n doesn't keep track of this information, then store_line_numbers\n is irrelevant.\n\n :param attribute_dict_class: The value of a multi-valued attribute\n (such as HTML's 'class') willl be stored in an instance of this\n class. The default is Beautiful Soup's built-in\n `AttributeValueList`, which is a normal Python list, and you\n will probably never need to change it.\n """\n\n USE_DEFAULT: Any = object() #: :meta private:\n\n def __init__(\n self,\n multi_valued_attributes: Dict[str, Set[str]] = USE_DEFAULT,\n preserve_whitespace_tags: Set[str] = USE_DEFAULT,\n store_line_numbers: bool = USE_DEFAULT,\n string_containers: Dict[str, Type[NavigableString]] = USE_DEFAULT,\n empty_element_tags: Set[str] = USE_DEFAULT,\n attribute_dict_class: Type[AttributeDict] = AttributeDict,\n attribute_value_list_class: Type[AttributeValueList] = AttributeValueList,\n ):\n self.soup = None\n if multi_valued_attributes is self.USE_DEFAULT:\n multi_valued_attributes = self.DEFAULT_CDATA_LIST_ATTRIBUTES\n self.cdata_list_attributes = multi_valued_attributes\n if preserve_whitespace_tags is self.USE_DEFAULT:\n preserve_whitespace_tags = self.DEFAULT_PRESERVE_WHITESPACE_TAGS\n self.preserve_whitespace_tags = preserve_whitespace_tags\n if empty_element_tags is self.USE_DEFAULT:\n self.empty_element_tags = self.DEFAULT_EMPTY_ELEMENT_TAGS\n else:\n self.empty_element_tags = empty_element_tags\n # TODO: store_line_numbers is probably irrelevant now that\n # the behavior of sourceline and sourcepos has been made consistent\n # everywhere.\n if store_line_numbers == self.USE_DEFAULT:\n store_line_numbers = self.TRACKS_LINE_NUMBERS\n self.store_line_numbers = store_line_numbers\n if string_containers == self.USE_DEFAULT:\n string_containers = self.DEFAULT_STRING_CONTAINERS\n self.string_containers = string_containers\n self.attribute_dict_class = attribute_dict_class\n self.attribute_value_list_class = attribute_value_list_class\n\n NAME: str = "[Unknown tree builder]"\n ALTERNATE_NAMES: Iterable[str] = []\n features: Iterable[str] = []\n\n is_xml: bool = False\n picklable: bool = False\n\n soup: Optional[BeautifulSoup] #: :meta private:\n\n #: A tag will be considered an empty-element\n #: tag when and only when it has no contents.\n empty_element_tags: Optional[Set[str]] = None #: :meta private:\n cdata_list_attributes: Dict[str, Set[str]] #: :meta private:\n preserve_whitespace_tags: Set[str] #: :meta private:\n string_containers: Dict[str, Type[NavigableString]] #: :meta private:\n tracks_line_numbers: bool #: :meta private:\n\n #: A value for these tag/attribute combinations is a space- or\n #: comma-separated list of CDATA, rather than a single CDATA.\n DEFAULT_CDATA_LIST_ATTRIBUTES: Dict[str, Set[str]] = defaultdict(set)\n\n #: Whitespace should be preserved inside these tags.\n DEFAULT_PRESERVE_WHITESPACE_TAGS: Set[str] = set()\n\n #: The textual contents of tags with these names should be\n #: instantiated with some class other than `bs4.element.NavigableString`.\n DEFAULT_STRING_CONTAINERS: Dict[str, Type[bs4.element.NavigableString]] = {}\n\n #: By default, tags are treated as empty-element tags if they have\n #: no contents--that is, using XML rules. HTMLTreeBuilder\n #: defines a different set of DEFAULT_EMPTY_ELEMENT_TAGS based on the\n #: HTML 4 and HTML5 standards.\n DEFAULT_EMPTY_ELEMENT_TAGS: Optional[Set[str]] = None\n\n #: Most parsers don't keep track of line numbers.\n TRACKS_LINE_NUMBERS: bool = False\n\n def initialize_soup(self, soup: BeautifulSoup) -> None:\n """The BeautifulSoup object has been initialized and is now\n being associated with the TreeBuilder.\n\n :param soup: A BeautifulSoup object.\n """\n self.soup = soup\n\n def reset(self) -> None:\n """Do any work necessary to reset the underlying parser\n for a new document.\n\n By default, this does nothing.\n """\n pass\n\n def can_be_empty_element(self, tag_name: str) -> bool:\n """Might a tag with this name be an empty-element tag?\n\n The final markup may or may not actually present this tag as\n self-closing.\n\n For instance: an HTMLBuilder does not consider a <p> tag to be\n an empty-element tag (it's not in\n HTMLBuilder.empty_element_tags). This means an empty <p> tag\n will be presented as "<p></p>", not "<p/>" or "<p>".\n\n The default implementation has no opinion about which tags are\n empty-element tags, so a tag will be presented as an\n empty-element tag if and only if it has no children.\n "<foo></foo>" will become "<foo/>", and "<foo>bar</foo>" will\n be left alone.\n\n :param tag_name: The name of a markup tag.\n """\n if self.empty_element_tags is None:\n return True\n return tag_name in self.empty_element_tags\n\n def feed(self, markup: _RawMarkup) -> None:\n """Run incoming markup through some parsing process."""\n raise NotImplementedError()\n\n def prepare_markup(\n self,\n markup: _RawMarkup,\n user_specified_encoding: Optional[_Encoding] = None,\n document_declared_encoding: Optional[_Encoding] = None,\n exclude_encodings: Optional[_Encodings] = None,\n ) -> Iterable[Tuple[_RawMarkup, Optional[_Encoding], Optional[_Encoding], bool]]:\n """Run any preliminary steps necessary to make incoming markup\n acceptable to the parser.\n\n :param markup: The markup that's about to be parsed.\n :param user_specified_encoding: The user asked to try this encoding\n to convert the markup into a Unicode string.\n :param document_declared_encoding: The markup itself claims to be\n in this encoding. NOTE: This argument is not used by the\n calling code and can probably be removed.\n :param exclude_encodings: The user asked *not* to try any of\n these encodings.\n\n :yield: A series of 4-tuples: (markup, encoding, declared encoding,\n has undergone character replacement)\n\n Each 4-tuple represents a strategy that the parser can try\n to convert the document to Unicode and parse it. Each\n strategy will be tried in turn.\n\n By default, the only strategy is to parse the markup\n as-is. See `LXMLTreeBuilderForXML` and\n `HTMLParserTreeBuilder` for implementations that take into\n account the quirks of particular parsers.\n\n :meta private:\n\n """\n yield markup, None, None, False\n\n def test_fragment_to_document(self, fragment: str) -> str:\n """Wrap an HTML fragment to make it look like a document.\n\n Different parsers do this differently. For instance, lxml\n introduces an empty <head> tag, and html5lib\n doesn't. Abstracting this away lets us write simple tests\n which run HTML fragments through the parser and compare the\n results against other HTML fragments.\n\n This method should not be used outside of unit tests.\n\n :param fragment: A fragment of HTML.\n :return: A full HTML document.\n :meta private:\n """\n return fragment\n\n def set_up_substitutions(self, tag: Tag) -> bool:\n """Set up any substitutions that will need to be performed on\n a `Tag` when it's output as a string.\n\n By default, this does nothing. See `HTMLTreeBuilder` for a\n case where this is used.\n\n :return: Whether or not a substitution was performed.\n :meta private:\n """\n return False\n\n def _replace_cdata_list_attribute_values(\n self, tag_name: str, attrs: _RawOrProcessedAttributeValues\n ) -> _AttributeValues:\n """When an attribute value is associated with a tag that can\n have multiple values for that attribute, convert the string\n value to a list of strings.\n\n Basically, replaces class="foo bar" with class=["foo", "bar"]\n\n NOTE: This method modifies its input in place.\n\n :param tag_name: The name of a tag.\n :param attrs: A dictionary containing the tag's attributes.\n Any appropriate attribute values will be modified in place.\n :return: The modified dictionary that was originally passed in.\n """\n\n # First, cast the attrs dict to _AttributeValues. This might\n # not be accurate yet, but it will be by the time this method\n # returns.\n modified_attrs = cast(_AttributeValues, attrs)\n if not modified_attrs or not self.cdata_list_attributes:\n # Nothing to do.\n return modified_attrs\n\n # There is at least a possibility that we need to modify one of\n # the attribute values.\n universal: Set[str] = self.cdata_list_attributes.get("*", set())\n tag_specific = self.cdata_list_attributes.get(tag_name.lower(), None)\n for attr in list(modified_attrs.keys()):\n modified_value: _AttributeValue\n if attr in universal or (tag_specific and attr in tag_specific):\n # We have a "class"-type attribute whose string\n # value is a whitespace-separated list of\n # values. Split it into a list.\n original_value: _AttributeValue = modified_attrs[attr]\n if isinstance(original_value, _RawAttributeValue):\n # This is a _RawAttributeValue (a string) that\n # needs to be split and converted to a\n # AttributeValueList so it can be an\n # _AttributeValue.\n modified_value = self.attribute_value_list_class(\n nonwhitespace_re.findall(original_value)\n )\n else:\n # html5lib calls setAttributes twice for the\n # same tag when rearranging the parse tree. On\n # the second call the attribute value here is\n # already a list. This can also happen when a\n # Tag object is cloned. If this happens, leave\n # the value alone rather than trying to split\n # it again.\n modified_value = original_value\n modified_attrs[attr] = modified_value\n return modified_attrs\n\n\nclass SAXTreeBuilder(TreeBuilder):\n """A Beautiful Soup treebuilder that listens for SAX events.\n\n This is not currently used for anything, and it will be removed\n soon. It was a good idea, but it wasn't properly integrated into the\n rest of Beautiful Soup, so there have been long stretches where it\n hasn't worked properly.\n """\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n warnings.warn(\n "The SAXTreeBuilder class was deprecated in 4.13.0 and will be removed soon thereafter. It is completely untested and probably doesn't work; do not use it.",\n DeprecationWarning,\n stacklevel=2,\n )\n super(SAXTreeBuilder, self).__init__(*args, **kwargs)\n\n def feed(self, markup: _RawMarkup) -> None:\n raise NotImplementedError()\n\n def close(self) -> None:\n pass\n\n def startElement(self, name: str, attrs: Dict[str, str]) -> None:\n attrs = AttributeDict((key[1], value) for key, value in list(attrs.items()))\n # print("Start %s, %r" % (name, attrs))\n assert self.soup is not None\n self.soup.handle_starttag(name, None, None, attrs)\n\n def endElement(self, name: str) -> None:\n # print("End %s" % name)\n assert self.soup is not None\n self.soup.handle_endtag(name)\n\n def startElementNS(\n self, nsTuple: Tuple[str, str], nodeName: str, attrs: Dict[str, str]\n ) -> None:\n # Throw away (ns, nodeName) for now.\n self.startElement(nodeName, attrs)\n\n def endElementNS(self, nsTuple: Tuple[str, str], nodeName: str) -> None:\n # Throw away (ns, nodeName) for now.\n self.endElement(nodeName)\n # handler.endElementNS((ns, node.nodeName), node.nodeName)\n\n def startPrefixMapping(self, prefix: str, nodeValue: str) -> None:\n # Ignore the prefix for now.\n pass\n\n def endPrefixMapping(self, prefix: str) -> None:\n # Ignore the prefix for now.\n # handler.endPrefixMapping(prefix)\n pass\n\n def characters(self, content: str) -> None:\n assert self.soup is not None\n self.soup.handle_data(content)\n\n def startDocument(self) -> None:\n pass\n\n def endDocument(self) -> None:\n pass\n\n\nclass HTMLTreeBuilder(TreeBuilder):\n """This TreeBuilder knows facts about HTML, such as which tags are treated\n specially by the HTML standard.\n """\n\n #: Some HTML tags are defined as having no contents. Beautiful Soup\n #: treats these specially.\n DEFAULT_EMPTY_ELEMENT_TAGS: Set[str] = set(\n [\n # These are from HTML5.\n "area",\n "base",\n "br",\n "col",\n "embed",\n "hr",\n "img",\n "input",\n "keygen",\n "link",\n "menuitem",\n "meta",\n "param",\n "source",\n "track",\n "wbr",\n # These are from earlier versions of HTML and are removed in HTML5.\n "basefont",\n "bgsound",\n "command",\n "frame",\n "image",\n "isindex",\n "nextid",\n "spacer",\n ]\n )\n\n #: The HTML standard defines these tags as block-level elements. Beautiful\n #: Soup does not treat these elements differently from other elements,\n #: but it may do so eventually, and this information is available if\n #: you need to use it.\n DEFAULT_BLOCK_ELEMENTS: Set[str] = set(\n [\n "address",\n "article",\n "aside",\n "blockquote",\n "canvas",\n "dd",\n "div",\n "dl",\n "dt",\n "fieldset",\n "figcaption",\n "figure",\n "footer",\n "form",\n "h1",\n "h2",\n "h3",\n "h4",\n "h5",\n "h6",\n "header",\n "hr",\n "li",\n "main",\n "nav",\n "noscript",\n "ol",\n "output",\n "p",\n "pre",\n "section",\n "table",\n "tfoot",\n "ul",\n "video",\n ]\n )\n\n #: These HTML tags need special treatment so they can be\n #: represented by a string class other than `bs4.element.NavigableString`.\n #:\n #: For some of these tags, it's because the HTML standard defines\n #: an unusual content model for them. I made this list by going\n #: through the HTML spec\n #: (https://html.spec.whatwg.org/#metadata-content) and looking for\n #: "metadata content" elements that can contain strings.\n #:\n #: The Ruby tags (<rt> and <rp>) are here despite being normal\n #: "phrasing content" tags, because the content they contain is\n #: qualitatively different from other text in the document, and it\n #: can be useful to be able to distinguish it.\n #:\n #: TODO: Arguably <noscript> could go here but it seems\n #: qualitatively different from the other tags.\n DEFAULT_STRING_CONTAINERS: Dict[str, Type[bs4.element.NavigableString]] = {\n "rt": RubyTextString,\n "rp": RubyParenthesisString,\n "style": Stylesheet,\n "script": Script,\n "template": TemplateString,\n }\n\n #: The HTML standard defines these attributes as containing a\n #: space-separated list of values, not a single value. That is,\n #: class="foo bar" means that the 'class' attribute has two values,\n #: 'foo' and 'bar', not the single value 'foo bar'. When we\n #: encounter one of these attributes, we will parse its value into\n #: a list of values if possible. Upon output, the list will be\n #: converted back into a string.\n DEFAULT_CDATA_LIST_ATTRIBUTES: Dict[str, Set[str]] = {\n "*": {"class", "accesskey", "dropzone"},\n "a": {"rel", "rev"},\n "link": {"rel", "rev"},\n "td": {"headers"},\n "th": {"headers"},\n "form": {"accept-charset"},\n "object": {"archive"},\n # These are HTML5 specific, as are *.accesskey and *.dropzone above.\n "area": {"rel"},\n "icon": {"sizes"},\n "iframe": {"sandbox"},\n "output": {"for"},\n }\n\n #: By default, whitespace inside these HTML tags will be\n #: preserved rather than being collapsed.\n DEFAULT_PRESERVE_WHITESPACE_TAGS: set[str] = set(["pre", "textarea"])\n\n def set_up_substitutions(self, tag: Tag) -> bool:\n """Replace the declared encoding in a <meta> tag with a placeholder,\n to be substituted when the tag is output to a string.\n\n An HTML document may come in to Beautiful Soup as one\n encoding, but exit in a different encoding, and the <meta> tag\n needs to be changed to reflect this.\n\n :return: Whether or not a substitution was performed.\n\n :meta private:\n """\n # We are only interested in <meta> tags\n if tag.name != "meta":\n return False\n\n # TODO: This cast will fail in the (very unlikely) scenario\n # that the programmer who instantiates the TreeBuilder\n # specifies meta['content'] or meta['charset'] as\n # cdata_list_attributes.\n content: Optional[str] = cast(Optional[str], tag.get("content"))\n charset: Optional[str] = cast(Optional[str], tag.get("charset"))\n\n # But we can accommodate meta['http-equiv'] being made a\n # cdata_list_attribute (again, very unlikely) without much\n # trouble.\n http_equiv: List[str] = tag.get_attribute_list("http-equiv")\n\n # We are interested in <meta> tags that say what encoding the\n # document was originally in. This means HTML 5-style <meta>\n # tags that provide the "charset" attribute. It also means\n # HTML 4-style <meta> tags that provide the "content"\n # attribute and have "http-equiv" set to "content-type".\n #\n # In both cases we will replace the value of the appropriate\n # attribute with a standin object that can take on any\n # encoding.\n substituted = False\n if charset is not None:\n # HTML 5 style:\n # <meta charset="utf8">\n tag["charset"] = CharsetMetaAttributeValue(charset)\n substituted = True\n\n elif content is not None and any(\n x.lower() == "content-type" for x in http_equiv\n ):\n # HTML 4 style:\n # <meta http-equiv="content-type" content="text/html; charset=utf8">\n tag["content"] = ContentMetaAttributeValue(content)\n substituted = True\n\n return substituted\n\n\nclass DetectsXMLParsedAsHTML(object):\n """A mixin class for any class (a TreeBuilder, or some class used by a\n TreeBuilder) that's in a position to detect whether an XML\n document is being incorrectly parsed as HTML, and issue an\n appropriate warning.\n\n This requires being able to observe an incoming processing\n instruction that might be an XML declaration, and also able to\n observe tags as they're opened. If you can't do that for a given\n `TreeBuilder`, there's a less reliable implementation based on\n examining the raw markup.\n """\n\n #: Regular expression for seeing if string markup has an <html> tag.\n LOOKS_LIKE_HTML: Pattern[str] = re.compile("<[^ +]html", re.I)\n\n #: Regular expression for seeing if byte markup has an <html> tag.\n LOOKS_LIKE_HTML_B: Pattern[bytes] = re.compile(b"<[^ +]html", re.I)\n\n #: The start of an XML document string.\n XML_PREFIX: str = "<?xml"\n\n #: The start of an XML document bytestring.\n XML_PREFIX_B: bytes = b"<?xml"\n\n # This is typed as str, not `ProcessingInstruction`, because this\n # check may be run before any Beautiful Soup objects are created.\n _first_processing_instruction: Optional[str] #: :meta private:\n _root_tag_name: Optional[str] #: :meta private:\n\n @classmethod\n def warn_if_markup_looks_like_xml(\n cls, markup: Optional[_RawMarkup], stacklevel: int = 3\n ) -> bool:\n """Perform a check on some markup to see if it looks like XML\n that's not XHTML. If so, issue a warning.\n\n This is much less reliable than doing the check while parsing,\n but some of the tree builders can't do that.\n\n :param stacklevel: The stacklevel of the code calling this\\n function.\n\n :return: True if the markup looks like non-XHTML XML, False\n otherwise.\n """\n if markup is None:\n return False\n markup = markup[:500]\n if isinstance(markup, bytes):\n markup_b: bytes = markup\n looks_like_xml = markup_b.startswith(\n cls.XML_PREFIX_B\n ) and not cls.LOOKS_LIKE_HTML_B.search(markup)\n else:\n markup_s: str = markup\n looks_like_xml = markup_s.startswith(\n cls.XML_PREFIX\n ) and not cls.LOOKS_LIKE_HTML.search(markup)\n\n if looks_like_xml:\n cls._warn(stacklevel=stacklevel + 2)\n return True\n return False\n\n @classmethod\n def _warn(cls, stacklevel: int = 5) -> None:\n """Issue a warning about XML being parsed as HTML."""\n warnings.warn(\n XMLParsedAsHTMLWarning.MESSAGE,\n XMLParsedAsHTMLWarning,\n stacklevel=stacklevel,\n )\n\n def _initialize_xml_detector(self) -> None:\n """Call this method before parsing a document."""\n self._first_processing_instruction = None\n self._root_tag_name = None\n\n def _document_might_be_xml(self, processing_instruction: str) -> None:\n """Call this method when encountering an XML declaration, or a\n "processing instruction" that might be an XML declaration.\n\n This helps Beautiful Soup detect potential issues later, if\n the XML document turns out to be a non-XHTML document that's\n being parsed as XML.\n """\n if (\n self._first_processing_instruction is not None\n or self._root_tag_name is not None\n ):\n # The document has already started. Don't bother checking\n # anymore.\n return\n\n self._first_processing_instruction = processing_instruction\n\n # We won't know until we encounter the first tag whether or\n # not this is actually a problem.\n\n def _root_tag_encountered(self, name: str) -> None:\n """Call this when you encounter the document's root tag.\n\n This is where we actually check whether an XML document is\n being incorrectly parsed as HTML, and issue the warning.\n """\n if self._root_tag_name is not None:\n # This method was incorrectly called multiple times. Do\n # nothing.\n return\n\n self._root_tag_name = name\n\n if (\n name != "html"\n and self._first_processing_instruction is not None\n and self._first_processing_instruction.lower().startswith("xml ")\n ):\n # We encountered an XML declaration and then a tag other\n # than 'html'. This is a reliable indicator that a\n # non-XHTML document is being parsed as XML.\n self._warn(stacklevel=10)\n\n\ndef register_treebuilders_from(module: ModuleType) -> None:\n """Copy TreeBuilders from the given module into this module."""\n this_module = sys.modules[__name__]\n for name in module.__all__:\n obj = getattr(module, name)\n\n if issubclass(obj, TreeBuilder):\n setattr(this_module, name, obj)\n this_module.__all__.append(name)\n # Register the builder while we're at it.\n this_module.builder_registry.register(obj)\n\n\n# Builders are registered in reverse order of priority, so that custom\n# builder registrations will take precedence. In general, we want lxml\n# to take precedence over html5lib, because it's faster. And we only\n# want to use HTMLParser as a last resort.\nfrom . import _htmlparser # noqa: E402\n\nregister_treebuilders_from(_htmlparser)\ntry:\n from . import _html5lib\n\n register_treebuilders_from(_html5lib)\nexcept ImportError:\n # They don't have html5lib installed.\n pass\ntry:\n from . import _lxml\n\n register_treebuilders_from(_lxml)\nexcept ImportError:\n # They don't have lxml installed.\n pass\n
|
.venv\Lib\site-packages\bs4\builder\__init__.py
|
__init__.py
|
Python
| 31,130 | 0.95 | 0.152123 | 0.189076 |
vue-tools
| 550 |
2025-03-05T00:23:12.954102
|
GPL-3.0
| false |
1eaf09f1b96a40d3559cf3dddb331c4a
|
\n\n
|
.venv\Lib\site-packages\bs4\builder\__pycache__\_html5lib.cpython-313.pyc
|
_html5lib.cpython-313.pyc
|
Other
| 23,319 | 0.95 | 0.019802 | 0.020725 |
awesome-app
| 377 |
2024-01-22T00:27:56.956568
|
Apache-2.0
| false |
3010966c48e0b52332a4342cdca34598
|
\n\n
|
.venv\Lib\site-packages\bs4\builder\__pycache__\_htmlparser.cpython-313.pyc
|
_htmlparser.cpython-313.pyc
|
Other
| 14,533 | 0.95 | 0.040462 | 0 |
awesome-app
| 17 |
2024-02-16T10:02:45.519752
|
GPL-3.0
| false |
52a79cacceb5e9710c06c99927916af9
|
\n\n
|
.venv\Lib\site-packages\bs4\builder\__pycache__\_lxml.cpython-313.pyc
|
_lxml.cpython-313.pyc
|
Other
| 18,530 | 0.8 | 0.068966 | 0.015152 |
awesome-app
| 870 |
2024-12-01T23:21:05.805360
|
BSD-3-Clause
| false |
b3662f168553b29eaf29f33e4a231138
|
\n\n
|
.venv\Lib\site-packages\bs4\builder\__pycache__\__init__.cpython-313.pyc
|
__init__.cpython-313.pyc
|
Other
| 26,902 | 0.95 | 0.105105 | 0 |
awesome-app
| 903 |
2024-05-09T12:38:02.123271
|
GPL-3.0
| false |
0f29675b7e0a4cb40eefd31580291390
|
import pytest\nfrom unittest.mock import patch\nfrom bs4.builder import DetectsXMLParsedAsHTML\n\n\nclass TestDetectsXMLParsedAsHTML:\n @pytest.mark.parametrize(\n "markup,looks_like_xml",\n [\n ("No xml declaration", False),\n ("<html>obviously HTML</html", False),\n ("<?xml ><html>Actually XHTML</html>", False),\n ("<?xml> < html>Tricky XHTML</html>", False),\n ("<?xml ><no-html-tag>", True),\n ],\n )\n def test_warn_if_markup_looks_like_xml(self, markup, looks_like_xml):\n # Test of our ability to guess at whether markup looks XML-ish\n # _and_ not HTML-ish.\n with patch("bs4.builder.DetectsXMLParsedAsHTML._warn") as mock:\n for data in markup, markup.encode("utf8"):\n result = DetectsXMLParsedAsHTML.warn_if_markup_looks_like_xml(data)\n assert result == looks_like_xml\n if looks_like_xml:\n assert mock.called\n else:\n assert not mock.called\n mock.reset_mock()\n
|
.venv\Lib\site-packages\bs4\tests\test_builder.py
|
test_builder.py
|
Python
| 1,095 | 0.95 | 0.142857 | 0.076923 |
react-lib
| 73 |
2023-12-29T00:12:33.881181
|
BSD-3-Clause
| true |
f35222511422298c17b9ca316af14cf3
|
"""Tests of the builder registry."""\n\nimport pytest\nimport warnings\nfrom typing import Type\n\nfrom bs4 import BeautifulSoup\nfrom bs4.builder import (\n builder_registry as registry,\n TreeBuilder,\n TreeBuilderRegistry,\n)\nfrom bs4.builder._htmlparser import HTMLParserTreeBuilder\n\nfrom . import (\n HTML5LIB_PRESENT,\n LXML_PRESENT,\n)\n\nif HTML5LIB_PRESENT:\n from bs4.builder._html5lib import HTML5TreeBuilder\n\nif LXML_PRESENT:\n from bs4.builder._lxml import (\n LXMLTreeBuilderForXML,\n LXMLTreeBuilder,\n )\n\n\n# TODO: Split out the lxml and html5lib tests into their own classes\n# and gate with pytest.mark.skipIf.\nclass TestBuiltInRegistry(object):\n """Test the built-in registry with the default builders registered."""\n\n def test_combination(self):\n assert registry.lookup("strict", "html") == HTMLParserTreeBuilder\n if LXML_PRESENT:\n assert registry.lookup("fast", "html") == LXMLTreeBuilder\n assert registry.lookup("permissive", "xml") == LXMLTreeBuilderForXML\n if HTML5LIB_PRESENT:\n assert registry.lookup("html5lib", "html") == HTML5TreeBuilder\n\n def test_lookup_by_markup_type(self):\n if LXML_PRESENT:\n assert registry.lookup("html") == LXMLTreeBuilder\n assert registry.lookup("xml") == LXMLTreeBuilderForXML\n else:\n assert registry.lookup("xml") is None\n if HTML5LIB_PRESENT:\n assert registry.lookup("html") == HTML5TreeBuilder\n else:\n assert registry.lookup("html") == HTMLParserTreeBuilder\n\n def test_named_library(self):\n if LXML_PRESENT:\n assert registry.lookup("lxml", "xml") == LXMLTreeBuilderForXML\n assert registry.lookup("lxml", "html") == LXMLTreeBuilder\n if HTML5LIB_PRESENT:\n assert registry.lookup("html5lib") == HTML5TreeBuilder\n\n assert registry.lookup("html.parser") == HTMLParserTreeBuilder\n\n def test_beautifulsoup_constructor_does_lookup(self):\n with warnings.catch_warnings(record=True):\n # This will create a warning about not explicitly\n # specifying a parser, but we'll ignore it.\n\n # You can pass in a string.\n BeautifulSoup("", features="html")\n # Or a list of strings.\n BeautifulSoup("", features=["html", "fast"])\n pass\n\n # You'll get an exception if BS can't find an appropriate\n # builder.\n with pytest.raises(ValueError):\n BeautifulSoup("", features="no-such-feature")\n\n\nclass TestRegistry(object):\n """Test the TreeBuilderRegistry class in general."""\n\n def setup_method(self):\n self.registry = TreeBuilderRegistry()\n\n def builder_for_features(self, *feature_list: str) -> Type[TreeBuilder]:\n cls = type(\n "Builder_" + "_".join(feature_list), (object,), {"features": feature_list}\n )\n\n self.registry.register(cls)\n return cls\n\n def test_register_with_no_features(self):\n builder = self.builder_for_features()\n\n # Since the builder advertises no features, you can't find it\n # by looking up features.\n assert self.registry.lookup("foo") is None\n\n # But you can find it by doing a lookup with no features, if\n # this happens to be the only registered builder.\n assert self.registry.lookup() == builder\n\n def test_register_with_features_makes_lookup_succeed(self):\n builder = self.builder_for_features("foo", "bar")\n assert self.registry.lookup("foo") is builder\n assert self.registry.lookup("bar") is builder\n\n def test_lookup_fails_when_no_builder_implements_feature(self):\n assert self.registry.lookup("baz") is None\n\n def test_lookup_gets_most_recent_registration_when_no_feature_specified(self):\n self.builder_for_features("foo")\n builder2 = self.builder_for_features("bar")\n assert self.registry.lookup() == builder2\n\n def test_lookup_fails_when_no_tree_builders_registered(self):\n assert self.registry.lookup() is None\n\n def test_lookup_gets_most_recent_builder_supporting_all_features(self):\n self.builder_for_features("foo")\n self.builder_for_features("bar")\n has_both_early = self.builder_for_features("foo", "bar", "baz")\n has_both_late = self.builder_for_features("foo", "bar", "quux")\n self.builder_for_features("bar")\n self.builder_for_features("foo")\n\n # There are two builders featuring 'foo' and 'bar', but\n # the one that also features 'quux' was registered later.\n assert self.registry.lookup("foo", "bar") == has_both_late\n\n # There is only one builder featuring 'foo', 'bar', and 'baz'.\n assert self.registry.lookup("foo", "bar", "baz") == has_both_early\n\n def test_lookup_fails_when_cannot_reconcile_requested_features(self):\n self.builder_for_features("foo", "bar")\n self.builder_for_features("foo", "baz")\n assert self.registry.lookup("bar", "baz") is None\n
|
.venv\Lib\site-packages\bs4\tests\test_builder_registry.py
|
test_builder_registry.py
|
Python
| 5,064 | 0.95 | 0.18705 | 0.137615 |
vue-tools
| 174 |
2024-05-20T06:19:02.284432
|
BSD-3-Clause
| true |
16ee52ed7b807f80874d0c828a86f6c8
|
# encoding: utf-8\nimport pytest\nimport logging\nimport warnings\nimport bs4\nfrom bs4 import BeautifulSoup\nfrom bs4.dammit import (\n EntitySubstitution,\n EncodingDetector,\n UnicodeDammit,\n)\n\n\nclass TestUnicodeDammit(object):\n """Standalone tests of UnicodeDammit."""\n\n def test_unicode_input(self):\n markup = "I'm already Unicode! \N{SNOWMAN}"\n dammit = UnicodeDammit(markup)\n assert dammit.unicode_markup == markup\n\n @pytest.mark.parametrize(\n "smart_quotes_to,expect_converted",\n [\n (None, "\u2018\u2019\u201c\u201d"),\n ("xml", "‘’“”"),\n ("html", "‘’“”"),\n ("ascii", "''" + '""'),\n ],\n )\n def test_smart_quotes_to(self, smart_quotes_to, expect_converted):\n """Verify the functionality of the smart_quotes_to argument\n to the UnicodeDammit constructor."""\n markup = b"<foo>\x91\x92\x93\x94</foo>"\n converted = UnicodeDammit(\n markup,\n known_definite_encodings=["windows-1252"],\n smart_quotes_to=smart_quotes_to,\n ).unicode_markup\n assert converted == "<foo>{}</foo>".format(expect_converted)\n\n def test_detect_utf8(self):\n utf8 = b"Sacr\xc3\xa9 bleu! \xe2\x98\x83"\n dammit = UnicodeDammit(utf8)\n assert dammit.original_encoding.lower() == "utf-8"\n assert dammit.unicode_markup == "Sacr\xe9 bleu! \N{SNOWMAN}"\n\n def test_convert_hebrew(self):\n hebrew = b"\xed\xe5\xec\xf9"\n dammit = UnicodeDammit(hebrew, ["iso-8859-8"])\n assert dammit.original_encoding.lower() == "iso-8859-8"\n assert dammit.unicode_markup == "\u05dd\u05d5\u05dc\u05e9"\n\n def test_dont_see_smart_quotes_where_there_are_none(self):\n utf_8 = b"\343\202\261\343\203\274\343\202\277\343\202\244 Watch"\n dammit = UnicodeDammit(utf_8)\n assert dammit.original_encoding.lower() == "utf-8"\n assert dammit.unicode_markup.encode("utf-8") == utf_8\n\n def test_ignore_inappropriate_codecs(self):\n utf8_data = "Räksmörgås".encode("utf-8")\n dammit = UnicodeDammit(utf8_data, ["iso-8859-8"])\n assert dammit.original_encoding.lower() == "utf-8"\n\n def test_ignore_invalid_codecs(self):\n utf8_data = "Räksmörgås".encode("utf-8")\n for bad_encoding in [".utf8", "...", "utF---16.!"]:\n dammit = UnicodeDammit(utf8_data, [bad_encoding])\n assert dammit.original_encoding.lower() == "utf-8"\n\n def test_exclude_encodings(self):\n # This is UTF-8.\n utf8_data = "Räksmörgås".encode("utf-8")\n\n # But if we exclude UTF-8 from consideration, the guess is\n # Windows-1252.\n dammit = UnicodeDammit(utf8_data, exclude_encodings=["utf-8"])\n assert dammit.original_encoding.lower() == "windows-1252"\n\n # And if we exclude that, there is no valid guess at all.\n dammit = UnicodeDammit(utf8_data, exclude_encodings=["utf-8", "windows-1252"])\n assert dammit.original_encoding is None\n\n\nclass TestEncodingDetector(object):\n def test_encoding_detector_replaces_junk_in_encoding_name_with_replacement_character(\n self,\n ):\n detected = EncodingDetector(b'<?xml version="1.0" encoding="UTF-\xdb" ?>')\n encodings = list(detected.encodings)\n assert "utf-\N{REPLACEMENT CHARACTER}" in encodings\n\n def test_detect_html5_style_meta_tag(self):\n for data in (\n b'<html><meta charset="euc-jp" /></html>',\n b"<html><meta charset='euc-jp' /></html>",\n b"<html><meta charset=euc-jp /></html>",\n b"<html><meta charset=euc-jp/></html>",\n ):\n dammit = UnicodeDammit(data, is_html=True)\n assert "euc-jp" == dammit.original_encoding\n\n def test_last_ditch_entity_replacement(self):\n # This is a UTF-8 document that contains bytestrings\n # completely incompatible with UTF-8 (ie. encoded with some other\n # encoding).\n #\n # Since there is no consistent encoding for the document,\n # Unicode, Dammit will eventually encode the document as UTF-8\n # and encode the incompatible characters as REPLACEMENT\n # CHARACTER.\n #\n # If chardet is installed, it will detect that the document\n # can be converted into ISO-8859-1 without errors. This happens\n # to be the wrong encoding, but it is a consistent encoding, so the\n # code we're testing here won't run.\n #\n # So we temporarily disable chardet if it's present.\n doc = b"""\357\273\277<?xml version="1.0" encoding="UTF-8"?>\n<html><b>\330\250\330\252\330\261</b>\n<i>\310\322\321\220\312\321\355\344</i></html>"""\n chardet = bs4.dammit._chardet_dammit\n logging.disable(logging.WARNING)\n try:\n\n def noop(str):\n return None\n\n bs4.dammit._chardet_dammit = noop\n dammit = UnicodeDammit(doc)\n assert True is dammit.contains_replacement_characters\n assert "\ufffd" in dammit.unicode_markup\n\n soup = BeautifulSoup(doc, "html.parser")\n assert soup.contains_replacement_characters\n finally:\n logging.disable(logging.NOTSET)\n bs4.dammit._chardet_dammit = chardet\n\n def test_byte_order_mark_removed(self):\n # A document written in UTF-16LE will have its byte order marker stripped.\n data = b"\xff\xfe<\x00a\x00>\x00\xe1\x00\xe9\x00<\x00/\x00a\x00>\x00"\n dammit = UnicodeDammit(data)\n assert "<a>áé</a>" == dammit.unicode_markup\n assert "utf-16le" == dammit.original_encoding\n\n def test_known_definite_versus_user_encodings(self):\n # The known_definite_encodings are used before sniffing the\n # byte-order mark; the user_encodings are used afterwards.\n\n # Here's a document in UTF-16LE.\n data = b"\xff\xfe<\x00a\x00>\x00\xe1\x00\xe9\x00<\x00/\x00a\x00>\x00"\n dammit = UnicodeDammit(data)\n\n # We can process it as UTF-16 by passing it in as a known\n # definite encoding.\n before = UnicodeDammit(data, known_definite_encodings=["utf-16"])\n assert "utf-16" == before.original_encoding\n\n # If we pass UTF-18 as a user encoding, it's not even\n # tried--the encoding sniffed from the byte-order mark takes\n # precedence.\n after = UnicodeDammit(data, user_encodings=["utf-8"])\n assert "utf-16le" == after.original_encoding\n assert ["utf-16le"] == [x[0] for x in dammit.tried_encodings]\n\n # Here's a document in ISO-8859-8.\n hebrew = b"\xed\xe5\xec\xf9"\n dammit = UnicodeDammit(\n hebrew, known_definite_encodings=["utf-8"], user_encodings=["iso-8859-8"]\n )\n\n # The known_definite_encodings don't work, BOM sniffing does\n # nothing (it only works for a few UTF encodings), but one of\n # the user_encodings does work.\n assert "iso-8859-8" == dammit.original_encoding\n assert ["utf-8", "iso-8859-8"] == [x[0] for x in dammit.tried_encodings]\n\n def test_deprecated_override_encodings(self):\n # override_encodings is a deprecated alias for\n # known_definite_encodings.\n hebrew = b"\xed\xe5\xec\xf9"\n with warnings.catch_warnings(record=True) as w:\n dammit = UnicodeDammit(\n hebrew,\n known_definite_encodings=["shift-jis"],\n override_encodings=["utf-8"],\n user_encodings=["iso-8859-8"],\n )\n [warning] = w\n message = warning.message\n assert isinstance(message, DeprecationWarning)\n assert warning.filename == __file__\n assert "iso-8859-8" == dammit.original_encoding\n\n # known_definite_encodings and override_encodings were tried\n # before user_encodings.\n assert ["shift-jis", "utf-8", "iso-8859-8"] == (\n [x[0] for x in dammit.tried_encodings]\n )\n\n def test_detwingle(self):\n # Here's a UTF8 document.\n utf8 = ("\N{SNOWMAN}" * 3).encode("utf8")\n\n # Here's a Windows-1252 document.\n windows_1252 = (\n "\N{LEFT DOUBLE QUOTATION MARK}Hi, I like Windows!"\n "\N{RIGHT DOUBLE QUOTATION MARK}"\n ).encode("windows_1252")\n\n # Through some unholy alchemy, they've been stuck together.\n doc = utf8 + windows_1252 + utf8\n\n # The document can't be turned into UTF-8:\n with pytest.raises(UnicodeDecodeError):\n doc.decode("utf8")\n\n # Unicode, Dammit thinks the whole document is Windows-1252,\n # and decodes it into "☃☃☃“Hi, I like Windows!”☃☃☃"\n\n # But if we run it through fix_embedded_windows_1252, it's fixed:\n fixed = UnicodeDammit.detwingle(doc)\n assert "☃☃☃“Hi, I like Windows!”☃☃☃" == fixed.decode("utf8")\n\n def test_detwingle_ignores_multibyte_characters(self):\n # Each of these characters has a UTF-8 representation ending\n # in \x93. \x93 is a smart quote if interpreted as\n # Windows-1252. But our code knows to skip over multibyte\n # UTF-8 characters, so they'll survive the process unscathed.\n for tricky_unicode_char in (\n "\N{LATIN SMALL LIGATURE OE}", # 2-byte char '\xc5\x93'\n "\N{LATIN SUBSCRIPT SMALL LETTER X}", # 3-byte char '\xe2\x82\x93'\n "\xf0\x90\x90\x93", # This is a CJK character, not sure which one.\n ):\n input = tricky_unicode_char.encode("utf8")\n assert input.endswith(b"\x93")\n output = UnicodeDammit.detwingle(input)\n assert output == input\n\n def test_find_declared_encoding(self):\n # Test our ability to find a declared encoding inside an\n # XML or HTML document.\n #\n # Even if the document comes in as Unicode, it may be\n # interesting to know what encoding was claimed\n # originally.\n\n html_unicode = '<html><head><meta charset="utf-8"></head></html>'\n html_bytes = html_unicode.encode("ascii")\n\n xml_unicode = '<?xml version="1.0" encoding="ISO-8859-1" ?>'\n xml_bytes = xml_unicode.encode("ascii")\n\n m = EncodingDetector.find_declared_encoding\n assert m(html_unicode, is_html=False) is None\n assert "utf-8" == m(html_unicode, is_html=True)\n assert "utf-8" == m(html_bytes, is_html=True)\n\n assert "iso-8859-1" == m(xml_unicode)\n assert "iso-8859-1" == m(xml_bytes)\n\n # Normally, only the first few kilobytes of a document are checked for\n # an encoding.\n spacer = b" " * 5000\n assert m(spacer + html_bytes) is None\n assert m(spacer + xml_bytes) is None\n\n # But you can tell find_declared_encoding to search an entire\n # HTML document.\n assert (\n m(spacer + html_bytes, is_html=True, search_entire_document=True) == "utf-8"\n )\n\n # The XML encoding declaration has to be the very first thing\n # in the document. We'll allow whitespace before the document\n # starts, but nothing else.\n assert m(xml_bytes, search_entire_document=True) == "iso-8859-1"\n assert m(b" " + xml_bytes, search_entire_document=True) == "iso-8859-1"\n assert m(b"a" + xml_bytes, search_entire_document=True) is None\n\n\nclass TestEntitySubstitution(object):\n """Standalone tests of the EntitySubstitution class."""\n\n def setup_method(self):\n self.sub = EntitySubstitution\n\n @pytest.mark.parametrize(\n "original,substituted",\n [\n # Basic case. Unicode characters corresponding to named\n # HTML entites are substituted; others are not.\n ("foo\u2200\N{SNOWMAN}\u00f5bar", "foo∀\N{SNOWMAN}õbar"),\n # MS smart quotes are a common source of frustration, so we\n # give them a special test.\n ("‘’foo“”", "‘’foo“”"),\n ],\n )\n def test_substitute_html(self, original, substituted):\n assert self.sub.substitute_html(original) == substituted\n\n def test_html5_entity(self):\n for entity, u in (\n # A few spot checks of our ability to recognize\n # special character sequences and convert them\n # to named entities.\n ("⊧", "\u22a7"),\n ("𝔑", "\U0001d511"),\n ("≧̸", "\u2267\u0338"),\n ("¬", "\xac"),\n ("⫬", "\u2aec"),\n # We _could_ convert | to &verbarr;, but we don't, because\n # | is an ASCII character.\n ("|" "|"),\n # Similarly for the fj ligature, which we could convert to\n # fj, but we don't.\n ("fj", "fj"),\n # We do convert _these_ ASCII characters to HTML entities,\n # because that's required to generate valid HTML.\n (">", ">"),\n ("<", "<"),\n ):\n template = "3 %s 4"\n raw = template % u\n with_entities = template % entity\n assert self.sub.substitute_html(raw) == with_entities\n\n def test_html5_entity_with_variation_selector(self):\n # Some HTML5 entities correspond either to a single-character\n # Unicode sequence _or_ to the same character plus U+FE00,\n # VARIATION SELECTOR 1. We can handle this.\n data = "fjords \u2294 penguins"\n markup = "fjords ⊔ penguins"\n assert self.sub.substitute_html(data) == markup\n\n data = "fjords \u2294\ufe00 penguins"\n markup = "fjords ⊔︀ penguins"\n assert self.sub.substitute_html(data) == markup\n\n def test_xml_converstion_includes_no_quotes_if_make_quoted_attribute_is_false(self):\n s = 'Welcome to "my bar"'\n assert self.sub.substitute_xml(s, False) == s\n\n def test_xml_attribute_quoting_normally_uses_double_quotes(self):\n assert self.sub.substitute_xml("Welcome", True) == '"Welcome"'\n assert self.sub.substitute_xml("Bob's Bar", True) == '"Bob\'s Bar"'\n\n def test_xml_attribute_quoting_uses_single_quotes_when_value_contains_double_quotes(\n self,\n ):\n s = 'Welcome to "my bar"'\n assert self.sub.substitute_xml(s, True) == "'Welcome to \"my bar\"'"\n\n def test_xml_attribute_quoting_escapes_single_quotes_when_value_contains_both_single_and_double_quotes(\n self,\n ):\n s = 'Welcome to "Bob\'s Bar"'\n assert self.sub.substitute_xml(s, True) == '"Welcome to "Bob\'s Bar""'\n\n def test_xml_quotes_arent_escaped_when_value_is_not_being_quoted(self):\n quoted = 'Welcome to "Bob\'s Bar"'\n assert self.sub.substitute_xml(quoted) == quoted\n\n def test_xml_quoting_handles_angle_brackets(self):\n assert self.sub.substitute_xml("foo<bar>") == "foo<bar>"\n\n def test_xml_quoting_handles_ampersands(self):\n assert self.sub.substitute_xml("AT&T") == "AT&T"\n\n def test_xml_quoting_including_ampersands_when_they_are_part_of_an_entity(self):\n assert self.sub.substitute_xml("ÁT&T") == "&Aacute;T&T"\n\n def test_xml_quoting_ignoring_ampersands_when_they_are_part_of_an_entity(self):\n assert (\n self.sub.substitute_xml_containing_entities("ÁT&T")\n == "ÁT&T"\n )\n\n def test_quotes_not_html_substituted(self):\n """There's no need to do this except inside attribute values."""\n text = 'Bob\'s "bar"'\n assert self.sub.substitute_html(text) == text\n\n @pytest.mark.parametrize(\n "markup, old",\n [\n ("foo & bar", "foo & bar"),\n ("foo&", "foo&"),\n ("foo&&& bar", "foo&&& bar"),\n ("x=1&y=2", "x=1&y=2"),\n ("&123", "&123"),\n ("&abc", "&abc"),\n ("foo &0 bar", "foo &0 bar"),\n ("foo &lolwat bar", "foo &lolwat bar"),\n ],\n )\n def test_unambiguous_ampersands_not_escaped(self, markup, old):\n assert self.sub.substitute_html(markup) == old\n assert self.sub.substitute_html5_raw(markup) == markup\n\n @pytest.mark.parametrize(\n "markup,html,html5,html5raw",\n [\n ("÷", "&divide;", "&divide;", "÷"),\n ("&nonesuch;", "&nonesuch;", "&nonesuch;", "&nonesuch;"),\n ("÷", "&#247;", "&#247;", "&#247;"),\n ("¡", "&#xa1;", "&#xa1;", "&#xa1;"),\n ],\n )\n def test_when_entity_ampersands_are_escaped(self, markup, html, html5, html5raw):\n # The html and html5 formatters always escape the ampersand\n # that begins an entity reference, because they assume\n # Beautiful Soup has already converted any unescaped entity references\n # to Unicode characters.\n #\n # The html5_raw formatter does not escape the ampersand that\n # begins a recognized HTML entity, because it does not\n # fit the HTML5 definition of an ambiguous ampersand.\n #\n # The html5_raw formatter does escape the ampersands in front\n # of unrecognized named entities, as well as numeric and\n # hexadecimal entities, because they do fit the definition.\n assert self.sub.substitute_html(markup) == html\n assert self.sub.substitute_html5(markup) == html5\n assert self.sub.substitute_html5_raw(markup) == html5raw\n\n @pytest.mark.parametrize(\n "markup,expect", [("&nosuchentity;", "&nosuchentity;")]\n )\n def test_ambiguous_ampersands_escaped(self, markup, expect):\n assert self.sub.substitute_html(markup) == expect\n assert self.sub.substitute_html5_raw(markup) == expect\n
|
.venv\Lib\site-packages\bs4\tests\test_dammit.py
|
test_dammit.py
|
Python
| 17,840 | 0.95 | 0.133949 | 0.240541 |
node-utils
| 112 |
2024-12-27T05:03:29.868501
|
GPL-3.0
| true |
8b9c85f42965e4bb5deeb264ad2fd335
|
"""Tests of classes in element.py.\n\nThe really big classes -- Tag, PageElement, and NavigableString --\nare tested in separate files.\n"""\n\nimport pytest\nfrom bs4.element import (\n HTMLAttributeDict,\n XMLAttributeDict,\n CharsetMetaAttributeValue,\n ContentMetaAttributeValue,\n NamespacedAttribute,\n ResultSet,\n)\n\nclass TestNamedspacedAttribute:\n def test_name_may_be_none_or_missing(self):\n a = NamespacedAttribute("xmlns", None)\n assert a == "xmlns"\n\n a = NamespacedAttribute("xmlns", "")\n assert a == "xmlns"\n\n a = NamespacedAttribute("xmlns")\n assert a == "xmlns"\n\n def test_namespace_may_be_none_or_missing(self):\n a = NamespacedAttribute(None, "tag")\n assert a == "tag"\n\n a = NamespacedAttribute("", "tag")\n assert a == "tag"\n\n def test_attribute_is_equivalent_to_colon_separated_string(self):\n a = NamespacedAttribute("a", "b")\n assert "a:b" == a\n\n def test_attributes_are_equivalent_if_prefix_and_name_identical(self):\n a = NamespacedAttribute("a", "b", "c")\n b = NamespacedAttribute("a", "b", "c")\n assert a == b\n\n # The actual namespace is not considered.\n c = NamespacedAttribute("a", "b", None)\n assert a == c\n\n # But name and prefix are important.\n d = NamespacedAttribute("a", "z", "c")\n assert a != d\n\n e = NamespacedAttribute("z", "b", "c")\n assert a != e\n\n\nclass TestAttributeValueWithCharsetSubstitution:\n """Certain attributes are designed to have the charset of the\n final document substituted into their value.\n """\n\n def test_charset_meta_attribute_value(self):\n # The value of a CharsetMetaAttributeValue is whatever\n # encoding the string is in.\n value = CharsetMetaAttributeValue("euc-jp")\n assert "euc-jp" == value\n assert "euc-jp" == value.original_value\n assert "utf8" == value.substitute_encoding("utf8")\n assert "ascii" == value.substitute_encoding("ascii")\n\n # If the target encoding is a Python internal encoding,\n # no encoding will be mentioned in the output HTML.\n assert "" == value.substitute_encoding("palmos")\n\n def test_content_meta_attribute_value(self):\n value = ContentMetaAttributeValue("text/html; charset=euc-jp")\n assert "text/html; charset=euc-jp" == value\n assert "text/html; charset=euc-jp" == value.original_value\n assert "text/html; charset=utf8" == value.substitute_encoding("utf8")\n assert "text/html; charset=ascii" == value.substitute_encoding("ascii")\n\n # If the target encoding is a Python internal encoding, the\n # charset argument will be omitted altogether.\n assert "text/html" == value.substitute_encoding("palmos")\n\n\nclass TestAttributeDicts:\n def test_xml_attribute_value_handling(self):\n # Verify that attribute values are processed according to the\n # XML spec's rules.\n d = XMLAttributeDict()\n d["v"] = 100\n assert d["v"] == "100"\n d["v"] = 100.123\n assert d["v"] == "100.123"\n\n # This preserves Beautiful Soup's old behavior in the absence of\n # guidance from the spec.\n d["v"] = False\n assert d["v"] is False\n\n d["v"] = True\n assert d["v"] is True\n\n d["v"] = None\n assert d["v"] == ""\n\n def test_html_attribute_value_handling(self):\n # Verify that attribute values are processed according to the\n # HTML spec's rules.\n d = HTMLAttributeDict()\n d["v"] = 100\n assert d["v"] == "100"\n d["v"] = 100.123\n assert d["v"] == "100.123"\n\n d["v"] = False\n assert "v" not in d\n\n d["v"] = None\n assert "v" not in d\n\n d["v"] = True\n assert d["v"] == "v"\n\n attribute = NamespacedAttribute("prefix", "name", "namespace")\n d[attribute] = True\n assert d[attribute] == "name"\n\n\nclass TestResultSet:\n def test_getattr_exception(self):\n rs = ResultSet(None)\n with pytest.raises(AttributeError) as e:\n rs.name\n assert (\n """ResultSet object has no attribute "name". You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?"""\n == str(e.value)\n )\n
|
.venv\Lib\site-packages\bs4\tests\test_element.py
|
test_element.py
|
Python
| 4,373 | 0.95 | 0.094203 | 0.12963 |
node-utils
| 171 |
2025-05-10T22:09:44.041827
|
BSD-3-Clause
| true |
a6bef2e7f8909569ea4d33389a303226
|
import pytest\n\nfrom bs4.element import Tag\nfrom bs4.formatter import (\n Formatter,\n HTMLFormatter,\n XMLFormatter,\n)\nfrom . import SoupTest\n\n\nclass TestFormatter(SoupTest):\n def test_default_attributes(self):\n # Test the default behavior of Formatter.attributes().\n formatter = Formatter()\n tag = Tag(name="tag")\n tag["b"] = "1"\n tag["a"] = "2"\n\n # Attributes come out sorted by name. In Python 3, attributes\n # normally come out of a dictionary in the order they were\n # added.\n assert [("a", "2"), ("b", "1")] == formatter.attributes(tag)\n\n # This works even if Tag.attrs is None, though this shouldn't\n # normally happen.\n tag.attrs = None\n assert [] == formatter.attributes(tag)\n\n assert " " == formatter.indent\n\n def test_sort_attributes(self):\n # Test the ability to override Formatter.attributes() to,\n # e.g., disable the normal sorting of attributes.\n class UnsortedFormatter(Formatter):\n def attributes(self, tag):\n self.called_with = tag\n for k, v in sorted(tag.attrs.items()):\n if k == "ignore":\n continue\n yield k, v\n\n soup = self.soup('<p cval="1" aval="2" ignore="ignored"></p>')\n formatter = UnsortedFormatter()\n decoded = soup.decode(formatter=formatter)\n\n # attributes() was called on the <p> tag. It filtered out one\n # attribute and sorted the other two.\n assert formatter.called_with == soup.p\n assert '<p aval="2" cval="1"></p>' == decoded\n\n def test_empty_attributes_are_booleans(self):\n # Test the behavior of empty_attributes_are_booleans as well\n # as which Formatters have it enabled.\n\n for name in ("html", "minimal", None):\n formatter = HTMLFormatter.REGISTRY[name]\n assert False is formatter.empty_attributes_are_booleans\n\n formatter = XMLFormatter.REGISTRY[None]\n assert False is formatter.empty_attributes_are_booleans\n\n formatter = HTMLFormatter.REGISTRY["html5"]\n assert True is formatter.empty_attributes_are_booleans\n\n # Verify that the constructor sets the value.\n formatter = Formatter(empty_attributes_are_booleans=True)\n assert True is formatter.empty_attributes_are_booleans\n\n # Now demonstrate what it does to markup.\n for markup in ("<option selected></option>", '<option selected=""></option>'):\n soup = self.soup(markup)\n for formatter in ("html", "minimal", "xml", None):\n assert b'<option selected=""></option>' == soup.option.encode(\n formatter="html"\n )\n assert b"<option selected></option>" == soup.option.encode(\n formatter="html5"\n )\n\n @pytest.mark.parametrize(\n "indent,expect",\n [\n (None, "<a>\n<b>\ntext\n</b>\n</a>\n"),\n (-1, "<a>\n<b>\ntext\n</b>\n</a>\n"),\n (0, "<a>\n<b>\ntext\n</b>\n</a>\n"),\n ("", "<a>\n<b>\ntext\n</b>\n</a>\n"),\n (1, "<a>\n <b>\n text\n </b>\n</a>\n"),\n (2, "<a>\n <b>\n text\n </b>\n</a>\n"),\n ("\t", "<a>\n\t<b>\n\t\ttext\n\t</b>\n</a>\n"),\n ("abc", "<a>\nabc<b>\nabcabctext\nabc</b>\n</a>\n"),\n # Some invalid inputs -- the default behavior is used.\n (object(), "<a>\n <b>\n text\n </b>\n</a>\n"),\n (b"bytes", "<a>\n <b>\n text\n </b>\n</a>\n"),\n ],\n )\n def test_indent(self, indent, expect):\n # Pretty-print a tree with a Formatter set to\n # indent in a certain way and verify the results.\n soup = self.soup("<a><b>text</b></a>")\n formatter = Formatter(indent=indent)\n assert soup.prettify(formatter=formatter) == expect\n\n # Pretty-printing only happens with prettify(), not\n # encode().\n assert soup.encode(formatter=formatter) != expect\n\n def test_default_indent_value(self):\n formatter = Formatter()\n assert formatter.indent == " "\n\n @pytest.mark.parametrize("formatter,expect",\n [\n (HTMLFormatter(indent=1), "<p>\n a\n</p>\n"),\n (HTMLFormatter(indent=2), "<p>\n a\n</p>\n"),\n (XMLFormatter(indent=1), "<p>\n a\n</p>\n"),\n (XMLFormatter(indent="\t"), "<p>\n\ta\n</p>\n"),\n ] )\n def test_indent_subclasses(self, formatter, expect):\n soup = self.soup("<p>a</p>")\n assert expect == soup.p.prettify(formatter=formatter)\n\n @pytest.mark.parametrize(\n "s,expect_html,expect_html5",\n [\n # The html5 formatter is much less aggressive about escaping ampersands\n # than the html formatter.\n ("foo & bar", "foo & bar", "foo & bar"),\n ("foo&", "foo&", "foo&"),\n ("foo&&& bar", "foo&&& bar", "foo&&& bar"),\n ("x=1&y=2", "x=1&y=2", "x=1&y=2"),\n ("&123", "&123", "&123"),\n ("&abc", "&abc", "&abc"),\n ("foo &0 bar", "foo &0 bar", "foo &0 bar"),\n ("foo &lolwat bar", "foo &lolwat bar", "foo &lolwat bar"),\n # But both formatters escape what the HTML5 spec considers ambiguous ampersands.\n ("&nosuchentity;", "&nosuchentity;", "&nosuchentity;"),\n ],\n )\n def test_entity_substitution(self, s, expect_html, expect_html5):\n assert HTMLFormatter.REGISTRY["html"].substitute(s) == expect_html\n assert HTMLFormatter.REGISTRY["html5"].substitute(s) == expect_html5\n assert HTMLFormatter.REGISTRY["html5-4.12"].substitute(s) == expect_html\n\n def test_entity_round_trip(self):\n # This is more an explanatory test and a way to avoid regressions than a test of functionality.\n\n markup = "<p>Some division signs: ÷ ÷ ÷ ÷. These are made with: ÷ &divide; &#247;</p>"\n soup = self.soup(markup)\n assert (\n "Some division signs: ÷ ÷ ÷ ÷. These are made with: ÷ ÷ ÷"\n == soup.p.string\n )\n\n # Oops, I forgot to mention the entity.\n soup.p.string = soup.p.string + " ÷"\n\n assert (\n "Some division signs: ÷ ÷ ÷ ÷. These are made with: ÷ ÷ ÷ ÷"\n == soup.p.string\n )\n\n expect = "<p>Some division signs: ÷ ÷ ÷ ÷. These are made with: ÷ &divide; &#247; &#xf7;</p>"\n assert expect == soup.p.decode(formatter="html")\n assert expect == soup.p.decode(formatter="html5")\n\n markup = "<p>a & b</p>"\n soup = self.soup(markup)\n assert "<p>a & b</p>" == soup.p.decode(formatter="html")\n assert "<p>a & b</p>" == soup.p.decode(formatter="html5")\n
|
.venv\Lib\site-packages\bs4\tests\test_formatter.py
|
test_formatter.py
|
Python
| 6,943 | 0.95 | 0.1 | 0.166667 |
node-utils
| 365 |
2023-07-25T03:50:44.861694
|
GPL-3.0
| true |
ab6dc4af15f58758f47e504eb919f635
|
"""This file contains test cases reported by third parties using\nfuzzing tools, primarily from Google's oss-fuzz project. Some of these\nrepresent real problems with Beautiful Soup, but many are problems in\nlibraries that Beautiful Soup depends on, and many of the test cases\nrepresent different ways of triggering the same problem.\n\nGrouping these test cases together makes it easy to see which test\ncases represent the same problem, and puts the test cases in close\nproximity to code that can trigger the problems.\n"""\n\nimport os\nimport importlib\nimport pytest\nfrom bs4 import (\n BeautifulSoup,\n ParserRejectedMarkup,\n)\n\ntry:\n from soupsieve.util import SelectorSyntaxError\n has_lxml = importlib.util.find_spec("lxml")\n has_html5lib = importlib.util.find_spec("html5lib")\n fully_fuzzable = has_lxml != None and has_html5lib != None\nexcept ImportError:\n fully_fuzzable = False\n\n\n@pytest.mark.skipif(\n not fully_fuzzable, reason="Prerequisites for fuzz tests are not installed."\n)\nclass TestFuzz(object):\n # Test case markup files from fuzzers are given this extension so\n # they can be included in builds.\n TESTCASE_SUFFIX = ".testcase"\n\n # Copied 20230512 from\n # https://github.com/google/oss-fuzz/blob/4ac6a645a197a695fe76532251feb5067076b3f3/projects/bs4/bs4_fuzzer.py\n #\n # Copying the code lets us precisely duplicate the behavior of\n # oss-fuzz. The downside is that this code changes over time, so\n # multiple copies of the code must be kept around to run against\n # older tests. I'm not sure what to do about this, but I may\n # retire old tests after a time.\n def fuzz_test_with_css(self, filename: str) -> None:\n data = self.__markup(filename)\n parsers = ["lxml-xml", "html5lib", "html.parser", "lxml"]\n try:\n idx = int(data[0]) % len(parsers)\n except ValueError:\n return\n\n css_selector, data = data[1:10], data[10:]\n\n try:\n soup = BeautifulSoup(data[1:], features=parsers[idx])\n except ParserRejectedMarkup:\n return\n except ValueError:\n return\n\n list(soup.find_all(True))\n try:\n soup.css.select(css_selector.decode("utf-8", "replace"))\n except SelectorSyntaxError:\n return\n soup.prettify()\n\n # This class of error has been fixed by catching a less helpful\n # exception from html.parser and raising ParserRejectedMarkup\n # instead.\n @pytest.mark.parametrize(\n "filename",\n [\n "clusterfuzz-testcase-minimized-bs4_fuzzer-5703933063462912",\n "crash-ffbdfa8a2b26f13537b68d3794b0478a4090ee4a",\n ],\n )\n def test_rejected_markup(self, filename):\n markup = self.__markup(filename)\n with pytest.raises(ParserRejectedMarkup):\n BeautifulSoup(markup, "html.parser")\n\n # This class of error has to do with very deeply nested documents\n # which overflow the Python call stack when the tree is converted\n # to a string. This is an issue with Beautiful Soup which was fixed\n # as part of [bug=1471755].\n #\n # These test cases are in the older format that doesn't specify\n # which parser to use or give a CSS selector.\n @pytest.mark.parametrize(\n "filename",\n [\n "clusterfuzz-testcase-minimized-bs4_fuzzer-5984173902397440",\n "clusterfuzz-testcase-minimized-bs4_fuzzer-5167584867909632",\n "clusterfuzz-testcase-minimized-bs4_fuzzer-6124268085182464",\n "clusterfuzz-testcase-minimized-bs4_fuzzer-6450958476902400",\n ],\n )\n def test_deeply_nested_document_without_css(self, filename):\n # Parsing the document and encoding it back to a string is\n # sufficient to demonstrate that the overflow problem has\n # been fixed.\n markup = self.__markup(filename)\n BeautifulSoup(markup, "html.parser").encode()\n\n # This class of error has to do with very deeply nested documents\n # which overflow the Python call stack when the tree is converted\n # to a string. This is an issue with Beautiful Soup which was fixed\n # as part of [bug=1471755].\n @pytest.mark.parametrize(\n "filename",\n [\n "clusterfuzz-testcase-minimized-bs4_fuzzer-5000587759190016",\n "clusterfuzz-testcase-minimized-bs4_fuzzer-5375146639360000",\n "clusterfuzz-testcase-minimized-bs4_fuzzer-5492400320282624",\n ],\n )\n def test_deeply_nested_document(self, filename):\n self.fuzz_test_with_css(filename)\n\n @pytest.mark.parametrize(\n "filename",\n [\n "clusterfuzz-testcase-minimized-bs4_fuzzer-4670634698080256",\n "clusterfuzz-testcase-minimized-bs4_fuzzer-5270998950477824",\n ],\n )\n def test_soupsieve_errors(self, filename):\n self.fuzz_test_with_css(filename)\n\n # This class of error represents problems with html5lib's parser,\n # not Beautiful Soup. I use\n # https://github.com/html5lib/html5lib-python/issues/568 to notify\n # the html5lib developers of these issues.\n #\n # These test cases are in the older format that doesn't specify\n # which parser to use or give a CSS selector.\n @pytest.mark.skip(reason="html5lib-specific problems")\n @pytest.mark.parametrize(\n "filename",\n [\n # b"""ÿ<!DOCTyPEV PUBLIC'''Ð'"""\n "clusterfuzz-testcase-minimized-bs4_fuzzer-4818336571064320",\n # b')<a><math><TR><a><mI><a><p><a>'\n "clusterfuzz-testcase-minimized-bs4_fuzzer-4999465949331456",\n # b'-<math><sElect><mi><sElect><sElect>'\n "clusterfuzz-testcase-minimized-bs4_fuzzer-5843991618256896",\n # b'ñ<table><svg><html>'\n "clusterfuzz-testcase-minimized-bs4_fuzzer-6241471367348224",\n # <TABLE>, some ^@ characters, some <math> tags.\n "clusterfuzz-testcase-minimized-bs4_fuzzer-6600557255327744",\n # Nested table\n "crash-0d306a50c8ed8bcd0785b67000fcd5dea1d33f08",\n ],\n )\n def test_html5lib_parse_errors_without_css(self, filename):\n markup = self.__markup(filename)\n print(BeautifulSoup(markup, "html5lib").encode())\n\n # This class of error represents problems with html5lib's parser,\n # not Beautiful Soup. I use\n # https://github.com/html5lib/html5lib-python/issues/568 to notify\n # the html5lib developers of these issues.\n @pytest.mark.skip(reason="html5lib-specific problems")\n @pytest.mark.parametrize(\n "filename",\n [\n # b'- \xff\xff <math>\x10<select><mi><select><select>t'\n "clusterfuzz-testcase-minimized-bs4_fuzzer-6306874195312640",\n ],\n )\n def test_html5lib_parse_errors(self, filename):\n self.fuzz_test_with_css(filename)\n\n def __markup(self, filename: str) -> bytes:\n if not filename.endswith(self.TESTCASE_SUFFIX):\n filename += self.TESTCASE_SUFFIX\n this_dir = os.path.split(__file__)[0]\n path = os.path.join(this_dir, "fuzz", filename)\n return open(path, "rb").read()\n
|
.venv\Lib\site-packages\bs4\tests\test_fuzz.py
|
test_fuzz.py
|
Python
| 7,123 | 0.95 | 0.110497 | 0.272727 |
node-utils
| 159 |
2023-07-24T20:27:55.379196
|
Apache-2.0
| true |
5db3f908f49748c1a10e0e240b066250
|
"""Tests to ensure that the html.parser tree builder generates good\ntrees."""\n\nimport pickle\nimport pytest\nfrom bs4.builder._htmlparser import (\n _DuplicateAttributeHandler,\n BeautifulSoupHTMLParser,\n HTMLParserTreeBuilder,\n)\nfrom bs4.exceptions import ParserRejectedMarkup\nfrom typing import Any\nfrom . import HTMLTreeBuilderSmokeTest\n\n\nclass TestHTMLParserTreeBuilder(HTMLTreeBuilderSmokeTest):\n default_builder = HTMLParserTreeBuilder\n\n def test_rejected_input(self):\n # Python's html.parser will occasionally reject markup,\n # especially when there is a problem with the initial DOCTYPE\n # declaration. Different versions of Python sound the alarm in\n # different ways, but Beautiful Soup consistently raises\n # errors as ParserRejectedMarkup exceptions.\n bad_markup = [\n # https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28873\n # https://github.com/guidovranken/python-library-fuzzers/blob/master/corp-html/519e5b4269a01185a0d5e76295251921da2f0700\n # https://github.com/python/cpython/issues/81928\n b"\n<![\xff\xfe\xfe\xcd\x00",\n # https://github.com/guidovranken/python-library-fuzzers/blob/master/corp-html/de32aa55785be29bbc72a1a8e06b00611fb3d9f8\n # https://github.com/python/cpython/issues/78661\n #\n b"<![n\x00",\n b"<![UNKNOWN[]]>",\n ]\n for markup in bad_markup:\n with pytest.raises(ParserRejectedMarkup):\n self.soup(markup)\n\n def test_namespaced_system_doctype(self):\n # html.parser can't handle namespaced doctypes, so skip this one.\n pass\n\n def test_namespaced_public_doctype(self):\n # html.parser can't handle namespaced doctypes, so skip this one.\n pass\n\n def test_builder_is_pickled(self):\n """Unlike most tree builders, HTMLParserTreeBuilder and will\n be restored after pickling.\n """\n tree = self.soup("<a><b>foo</a>")\n dumped = pickle.dumps(tree, 2)\n loaded = pickle.loads(dumped)\n assert isinstance(loaded.builder, type(tree.builder))\n\n def test_redundant_empty_element_closing_tags(self):\n self.assert_soup("<br></br><br></br><br></br>", "<br/><br/><br/>")\n self.assert_soup("</br></br></br>", "")\n\n def test_empty_element(self):\n # This verifies that any buffered data present when the parser\n # finishes working is handled.\n self.assert_soup("foo &# bar", "foo &# bar")\n\n def test_tracking_line_numbers(self):\n # The html.parser TreeBuilder keeps track of line number and\n # position of each element.\n markup = "\n <p>\n\n<sourceline>\n<b>text</b></sourceline><sourcepos></p>"\n soup = self.soup(markup)\n assert 2 == soup.p.sourceline\n assert 3 == soup.p.sourcepos\n assert "sourceline" == soup.p.find("sourceline").name\n\n # You can deactivate this behavior.\n soup = self.soup(markup, store_line_numbers=False)\n assert None is soup.p.sourceline\n assert None is soup.p.sourcepos\n\n def test_on_duplicate_attribute(self):\n # The html.parser tree builder has a variety of ways of\n # handling a tag that contains the same attribute multiple times.\n\n markup = '<a class="cls" href="url1" href="url2" href="url3" id="id">'\n\n # If you don't provide any particular value for\n # on_duplicate_attribute, later values replace earlier values.\n soup = self.soup(markup)\n assert "url3" == soup.a["href"]\n assert ["cls"] == soup.a["class"]\n assert "id" == soup.a["id"]\n\n # You can also get this behavior explicitly.\n def assert_attribute(\n on_duplicate_attribute: _DuplicateAttributeHandler, expected: Any\n ) -> None:\n soup = self.soup(markup, on_duplicate_attribute=on_duplicate_attribute)\n assert soup.a is not None\n assert expected == soup.a["href"]\n\n # Verify that non-duplicate attributes are treated normally.\n assert ["cls"] == soup.a["class"]\n assert "id" == soup.a["id"]\n\n assert_attribute(None, "url3")\n assert_attribute(BeautifulSoupHTMLParser.REPLACE, "url3")\n\n # You can ignore subsequent values in favor of the first.\n assert_attribute(BeautifulSoupHTMLParser.IGNORE, "url1")\n\n # And you can pass in a callable that does whatever you want.\n def accumulate(attrs, key, value):\n if not isinstance(attrs[key], list):\n attrs[key] = [attrs[key]]\n attrs[key].append(value)\n\n assert_attribute(accumulate, ["url1", "url2", "url3"])\n\n def test_html5_attributes(self):\n # The html.parser TreeBuilder can convert any entity named in\n # the HTML5 spec to a sequence of Unicode characters, and\n # convert those Unicode characters to a (potentially\n # different) named entity on the way out.\n for input_element, output_unicode, output_element in (\n ("⇄", "\u21c4", b"⇄"),\n ("⊧", "\u22a7", b"⊧"),\n ("𝔑", "\U0001d511", b"𝔑"),\n ("≧̸", "\u2267\u0338", b"≧̸"),\n ("¬", "\xac", b"¬"),\n ("⫬", "\u2aec", b"⫬"),\n (""", '"', b'"'),\n ("∴", "\u2234", b"∴"),\n ("∴", "\u2234", b"∴"),\n ("∴", "\u2234", b"∴"),\n ("fj", "fj", b"fj"),\n ("⊔", "\u2294", b"⊔"),\n ("⊔︀", "\u2294\ufe00", b"⊔︀"),\n ("'", "'", b"'"),\n ("|", "|", b"|"),\n ):\n markup = "<div>%s</div>" % input_element\n div = self.soup(markup).div\n without_element = div.encode()\n expect = b"<div>%s</div>" % output_unicode.encode("utf8")\n assert without_element == expect\n\n with_element = div.encode(formatter="html")\n expect = b"<div>%s</div>" % output_element\n assert with_element == expect\n\n def test_invalid_html_entity(self):\n # The html.parser treebuilder can't distinguish between an invalid\n # HTML entity with a semicolon and an invalid HTML entity with no\n # semicolon.\n markup = "<p>a &nosuchentity b</p>"\n soup = self.soup(markup)\n assert "<p>a &nosuchentity b</p>" == soup.p.decode()\n\n markup = "<p>a &nosuchentity; b</p>"\n soup = self.soup(markup)\n assert "<p>a &nosuchentity b</p>" == soup.p.decode()\n
|
.venv\Lib\site-packages\bs4\tests\test_htmlparser.py
|
test_htmlparser.py
|
Python
| 6,662 | 0.95 | 0.124224 | 0.240876 |
react-lib
| 385 |
2024-06-02T04:44:46.930544
|
MIT
| true |
6e90d868202e79eda53fd765e5703b05
|
"""Tests to ensure that the lxml tree builder generates good trees."""\n\nimport pickle\nimport pytest\nimport warnings\nfrom . import LXML_PRESENT, LXML_VERSION\n\nif LXML_PRESENT:\n from bs4.builder._lxml import LXMLTreeBuilder, LXMLTreeBuilderForXML\n\nfrom bs4 import (\n BeautifulStoneSoup,\n)\nfrom . import (\n HTMLTreeBuilderSmokeTest,\n XMLTreeBuilderSmokeTest,\n SOUP_SIEVE_PRESENT,\n)\n\n\n@pytest.mark.skipif(\n not LXML_PRESENT,\n reason="lxml seems not to be present, not testing its tree builder.",\n)\nclass TestLXMLTreeBuilder(HTMLTreeBuilderSmokeTest):\n """See ``HTMLTreeBuilderSmokeTest``."""\n\n @property\n def default_builder(self):\n return LXMLTreeBuilder\n\n def test_out_of_range_entity(self):\n self.assert_soup("<p>foo�bar</p>", "<p>foobar</p>")\n self.assert_soup("<p>foo�bar</p>", "<p>foobar</p>")\n self.assert_soup("<p>foo�bar</p>", "<p>foobar</p>")\n\n def test_entities_in_foreign_document_encoding(self):\n # We can't implement this case correctly because by the time we\n # hear about markup like "“", it's been (incorrectly) converted into\n # a string like u'\x93'\n pass\n\n # In lxml < 2.3.5, an empty doctype causes a segfault. Skip this\n # test if an old version of lxml is installed.\n\n @pytest.mark.skipif(\n not LXML_PRESENT or LXML_VERSION < (2, 3, 5, 0),\n reason="Skipping doctype test for old version of lxml to avoid segfault.",\n )\n def test_empty_doctype(self):\n soup = self.soup("<!DOCTYPE>")\n doctype = soup.contents[0]\n assert "" == doctype.strip()\n\n def test_beautifulstonesoup_is_xml_parser(self):\n # Make sure that the deprecated BSS class uses an xml builder\n # if one is installed.\n with warnings.catch_warnings(record=True) as w:\n soup = BeautifulStoneSoup("<b />")\n assert "<b/>" == str(soup.b)\n [warning] = w\n assert warning.filename == __file__\n assert "The BeautifulStoneSoup class was deprecated" in str(warning.message)\n\n def test_tracking_line_numbers(self):\n # The lxml TreeBuilder cannot keep track of line numbers from\n # the original markup. Even if you ask for line numbers, we\n # don't have 'em.\n #\n # However, for consistency with other parsers, Tag.sourceline\n # and Tag.sourcepos are always set to None, rather than being\n # available as an alias for find().\n soup = self.soup(\n "\n <p>\n\n<sourceline>\n<b>text</b></sourceline><sourcepos></p>",\n store_line_numbers=True,\n )\n assert None is soup.p.sourceline\n assert None is soup.p.sourcepos\n\n\n@pytest.mark.skipif(\n not LXML_PRESENT,\n reason="lxml seems not to be present, not testing its XML tree builder.",\n)\nclass TestLXMLXMLTreeBuilder(XMLTreeBuilderSmokeTest):\n """See ``HTMLTreeBuilderSmokeTest``."""\n\n @property\n def default_builder(self):\n return LXMLTreeBuilderForXML\n\n def test_namespace_indexing(self):\n soup = self.soup(\n '<?xml version="1.1"?>\n'\n "<root>"\n '<tag xmlns="http://unprefixed-namespace.com">content</tag>'\n '<prefix:tag2 xmlns:prefix="http://prefixed-namespace.com">content</prefix:tag2>'\n '<prefix2:tag3 xmlns:prefix2="http://another-namespace.com">'\n '<subtag xmlns="http://another-unprefixed-namespace.com">'\n '<subsubtag xmlns="http://yet-another-unprefixed-namespace.com">'\n "</prefix2:tag3>"\n "</root>"\n )\n\n # The BeautifulSoup object includes every namespace prefix\n # defined in the entire document. This is the default set of\n # namespaces used by soupsieve.\n #\n # Un-prefixed namespaces are not included, and if a given\n # prefix is defined twice, only the first prefix encountered\n # in the document shows up here.\n assert soup._namespaces == {\n "xml": "http://www.w3.org/XML/1998/namespace",\n "prefix": "http://prefixed-namespace.com",\n "prefix2": "http://another-namespace.com",\n }\n\n # A Tag object includes only the namespace prefixes\n # that were in scope when it was parsed.\n\n # We do not track un-prefixed namespaces as we can only hold\n # one (the first one), and it will be recognized as the\n # default namespace by soupsieve, even when operating from a\n # tag with a different un-prefixed namespace.\n assert soup.tag._namespaces == {\n "xml": "http://www.w3.org/XML/1998/namespace",\n }\n\n assert soup.tag2._namespaces == {\n "prefix": "http://prefixed-namespace.com",\n "xml": "http://www.w3.org/XML/1998/namespace",\n }\n\n assert soup.subtag._namespaces == {\n "prefix2": "http://another-namespace.com",\n "xml": "http://www.w3.org/XML/1998/namespace",\n }\n\n assert soup.subsubtag._namespaces == {\n "prefix2": "http://another-namespace.com",\n "xml": "http://www.w3.org/XML/1998/namespace",\n }\n\n @pytest.mark.skipif(not SOUP_SIEVE_PRESENT, reason="Soup Sieve not installed")\n def test_namespace_interaction_with_select_and_find(self):\n # Demonstrate how namespaces interact with select* and\n # find* methods.\n\n soup = self.soup(\n '<?xml version="1.1"?>\n'\n "<root>"\n '<tag xmlns="http://unprefixed-namespace.com">content</tag>'\n '<prefix:tag2 xmlns:prefix="http://prefixed-namespace.com">content</tag>'\n '<subtag xmlns:prefix="http://another-namespace-same-prefix.com">'\n "<prefix:tag3>"\n "</subtag>"\n "</root>"\n )\n\n # soupselect uses namespace URIs.\n assert soup.select_one("tag").name == "tag"\n assert soup.select_one("prefix|tag2").name == "tag2"\n\n # If a prefix is declared more than once, only the first usage\n # is registered with the BeautifulSoup object.\n assert soup.select_one("prefix|tag3") is None\n\n # But you can always explicitly specify a namespace dictionary.\n assert (\n soup.select_one("prefix|tag3", namespaces=soup.subtag._namespaces).name\n == "tag3"\n )\n\n # And a Tag (as opposed to the BeautifulSoup object) will\n # have a set of default namespaces scoped to that Tag.\n assert soup.subtag.select_one("prefix|tag3").name == "tag3"\n\n # the find() methods aren't fully namespace-aware; they just\n # look at prefixes.\n assert soup.find("tag").name == "tag"\n assert soup.find("prefix:tag2").name == "tag2"\n assert soup.find("prefix:tag3").name == "tag3"\n assert soup.subtag.find("prefix:tag3").name == "tag3"\n\n def test_pickle_restores_builder(self):\n # The lxml TreeBuilder is not picklable, so when unpickling\n # a document created with it, a new TreeBuilder of the\n # appropriate class is created.\n soup = self.soup("<a>some markup</a>")\n assert isinstance(soup.builder, self.default_builder)\n pickled = pickle.dumps(soup)\n unpickled = pickle.loads(pickled)\n\n assert "some markup" == unpickled.a.string\n assert unpickled.builder != soup.builder\n assert isinstance(unpickled.builder, self.default_builder)\n
|
.venv\Lib\site-packages\bs4\tests\test_lxml.py
|
test_lxml.py
|
Python
| 7,453 | 0.95 | 0.122449 | 0.242424 |
awesome-app
| 807 |
2023-11-29T00:52:34.079231
|
Apache-2.0
| true |
54eb60d65c938c264c716509243575ab
|
import pytest\n\nfrom bs4.element import (\n CData,\n Comment,\n Declaration,\n Doctype,\n NavigableString,\n RubyParenthesisString,\n RubyTextString,\n Script,\n Stylesheet,\n TemplateString,\n)\n\nfrom . import SoupTest\n\n\nclass TestNavigableString(SoupTest):\n def test_text_acquisition_methods(self):\n # These methods are intended for use against Tag, but they\n # work on NavigableString as well,\n\n s = NavigableString("fee ")\n cdata = CData("fie ")\n comment = Comment("foe ")\n\n assert "fee " == s.get_text()\n assert "fee " == s.string\n assert "fee" == s.get_text(strip=True)\n assert ["fee "] == list(s.strings)\n assert ["fee"] == list(s.stripped_strings)\n assert ["fee "] == list(s._all_strings())\n\n assert "fie " == cdata.get_text()\n assert "fie " == cdata.string\n assert "fie" == cdata.get_text(strip=True)\n assert ["fie "] == list(cdata.strings)\n assert ["fie"] == list(cdata.stripped_strings)\n assert ["fie "] == list(cdata._all_strings())\n\n # Since a Comment isn't normally considered 'text',\n # these methods generally do nothing.\n assert "" == comment.get_text()\n assert [] == list(comment.strings)\n assert [] == list(comment.stripped_strings)\n assert [] == list(comment._all_strings())\n\n # Unless you specifically say that comments are okay.\n assert "foe" == comment.get_text(strip=True, types=Comment)\n assert "foe " == comment.get_text(types=(Comment, NavigableString))\n\n def test_string_has_immutable_name_property(self):\n # string.name is defined as None and can't be modified\n string = self.soup("s").string\n assert None is string.name\n with pytest.raises(AttributeError):\n string.name = "foo"\n\n def test_string_detects_attribute_access_attempt(self):\n string = self.soup("the string").string\n\n # Try to access an HTML attribute of a NavigableString and get a helpful exception.\n with pytest.raises(TypeError) as e:\n string["attr"]\n assert str(e.value) == "string indices must be integers, not 'str'. Are you treating a NavigableString like a Tag?"\n\n # Normal string access works.\n assert string[2] == "e"\n assert string[2:5] == "e s"\n\nclass TestNavigableStringSubclasses(SoupTest):\n def test_cdata(self):\n # None of the current builders turn CDATA sections into CData\n # objects, but you can create them manually.\n soup = self.soup("")\n cdata = CData("foo")\n soup.insert(1, cdata)\n assert str(soup) == "<![CDATA[foo]]>"\n assert soup.find(string="foo") == "foo"\n assert soup.contents[0] == "foo"\n\n def test_cdata_is_never_formatted(self):\n """Text inside a CData object is passed into the formatter.\n\n But the return value is ignored.\n """\n\n self.count = 0\n\n def increment(*args):\n self.count += 1\n return "BITTER FAILURE"\n\n soup = self.soup("")\n cdata = CData("<><><>")\n soup.insert(1, cdata)\n assert b"<![CDATA[<><><>]]>" == soup.encode(formatter=increment)\n assert 1 == self.count\n\n def test_doctype_ends_in_newline(self):\n # Unlike other NavigableString subclasses, a DOCTYPE always ends\n # in a newline.\n doctype = Doctype("foo")\n soup = self.soup("")\n soup.insert(1, doctype)\n assert soup.encode() == b"<!DOCTYPE foo>\n"\n\n def test_declaration(self):\n d = Declaration("foo")\n assert "<?foo?>" == d.output_ready()\n\n def test_default_string_containers(self):\n # In some cases, we use different NavigableString subclasses for\n # the same text in different tags.\n soup = self.soup("<div>text</div><script>text</script><style>text</style>")\n assert [NavigableString, Script, Stylesheet] == [\n x.__class__ for x in soup.find_all(string=True)\n ]\n\n # The TemplateString is a little unusual because it's generally found\n # _inside_ children of a <template> element, not a direct child of the\n # <template> element.\n soup = self.soup(\n "<template>Some text<p>In a tag</p></template>Some text outside"\n )\n assert all(\n isinstance(x, TemplateString)\n for x in soup.template._all_strings(types=None)\n )\n\n # Once the <template> tag closed, we went back to using\n # NavigableString.\n outside = soup.template.next_sibling\n assert isinstance(outside, NavigableString)\n assert not isinstance(outside, TemplateString)\n\n # The TemplateString is also unusual because it can contain\n # NavigableString subclasses of _other_ types, such as\n # Comment.\n markup = b"<template>Some text<p>In a tag</p><!--with a comment--></template>"\n soup = self.soup(markup)\n assert markup == soup.template.encode("utf8")\n\n def test_ruby_strings(self):\n markup = "<ruby>漢 <rp>(</rp><rt>kan</rt><rp>)</rp> 字 <rp>(</rp><rt>ji</rt><rp>)</rp></ruby>"\n soup = self.soup(markup)\n assert isinstance(soup.rp.string, RubyParenthesisString)\n assert isinstance(soup.rt.string, RubyTextString)\n\n # Just as a demo, here's what this means for get_text usage.\n assert "漢字" == soup.get_text(strip=True)\n assert "漢(kan)字(ji)" == soup.get_text(\n strip=True, types=(NavigableString, RubyTextString, RubyParenthesisString)\n )\n
|
.venv\Lib\site-packages\bs4\tests\test_navigablestring.py
|
test_navigablestring.py
|
Python
| 5,599 | 0.95 | 0.109677 | 0.179688 |
node-utils
| 860 |
2025-05-14T01:41:26.100977
|
MIT
| true |
b57c9b544208774efa3695425d8fd021
|
# -*- coding: utf-8 -*-\n"""Tests of Beautiful Soup as a whole."""\n\nimport logging\nimport pickle\nimport pytest\nfrom typing import Iterable\n\nfrom bs4 import (\n BeautifulSoup,\n GuessedAtParserWarning,\n dammit,\n)\nfrom bs4.builder import (\n TreeBuilder,\n)\nfrom bs4.element import (\n AttributeValueList,\n XMLAttributeDict,\n Comment,\n PYTHON_SPECIFIC_ENCODINGS,\n Tag,\n NavigableString,\n)\nfrom bs4.filter import SoupStrainer\nfrom bs4.exceptions import (\n ParserRejectedMarkup,\n)\nfrom bs4._warnings import (\n MarkupResemblesLocatorWarning,\n)\n\n\nfrom . import (\n default_builder,\n LXML_PRESENT,\n SoupTest,\n)\nimport warnings\nfrom typing import Type\n\n\nclass TestConstructor(SoupTest):\n def test_short_unicode_input(self):\n data = "<h1>éé</h1>"\n soup = self.soup(data)\n assert "éé" == soup.h1.string\n\n def test_embedded_null(self):\n data = "<h1>foo\0bar</h1>"\n soup = self.soup(data)\n assert "foo\0bar" == soup.h1.string\n\n def test_exclude_encodings(self):\n utf8_data = "Räksmörgås".encode("utf-8")\n soup = self.soup(utf8_data, exclude_encodings=["utf-8"])\n assert "windows-1252" == soup.original_encoding\n\n def test_custom_builder_class(self):\n # Verify that you can pass in a custom Builder class and\n # it'll be instantiated with the appropriate keyword arguments.\n class Mock(object):\n def __init__(self, **kwargs):\n self.called_with = kwargs\n self.is_xml = True\n self.store_line_numbers = False\n self.cdata_list_attributes = []\n self.preserve_whitespace_tags = []\n self.string_containers = {}\n self.attribute_dict_class = XMLAttributeDict\n self.attribute_value_list_class = AttributeValueList\n\n def initialize_soup(self, soup):\n pass\n\n def feed(self, markup):\n self.fed = markup\n\n def reset(self):\n pass\n\n def ignore(self, ignore):\n pass\n\n set_up_substitutions = can_be_empty_element = ignore\n\n def prepare_markup(self, *args, **kwargs):\n yield (\n "prepared markup",\n "original encoding",\n "declared encoding",\n "contains replacement characters",\n )\n\n kwargs = dict(\n var="value",\n # This is a deprecated BS3-era keyword argument, which\n # will be stripped out.\n convertEntities=True,\n )\n with warnings.catch_warnings(record=True):\n soup = BeautifulSoup("", builder=Mock, **kwargs)\n assert isinstance(soup.builder, Mock)\n assert dict(var="value") == soup.builder.called_with\n assert "prepared markup" == soup.builder.fed\n\n # You can also instantiate the TreeBuilder yourself. In this\n # case, that specific object is used and any keyword arguments\n # to the BeautifulSoup constructor are ignored.\n builder = Mock(**kwargs)\n with warnings.catch_warnings(record=True) as w:\n soup = BeautifulSoup(\n "",\n builder=builder,\n ignored_value=True,\n )\n msg = str(w[0].message)\n assert msg.startswith(\n "Keyword arguments to the BeautifulSoup constructor will be ignored."\n )\n assert builder == soup.builder\n assert kwargs == builder.called_with\n\n def test_parser_markup_rejection(self):\n # If markup is completely rejected by the parser, an\n # explanatory ParserRejectedMarkup exception is raised.\n class Mock(TreeBuilder):\n def feed(self, *args, **kwargs):\n raise ParserRejectedMarkup("Nope.")\n\n def prepare_markup(self, markup, *args, **kwargs):\n # We're going to try two different ways of preparing this markup,\n # but feed() will reject both of them.\n yield markup, None, None, False\n yield markup, None, None, False\n\n\n with pytest.raises(ParserRejectedMarkup) as exc_info:\n BeautifulSoup("", builder=Mock)\n assert (\n "The markup you provided was rejected by the parser. Trying a different parser or a different encoding may help."\n in str(exc_info.value)\n )\n\n def test_cdata_list_attributes(self):\n # Most attribute values are represented as scalars, but the\n # HTML standard says that some attributes, like 'class' have\n # space-separated lists as values.\n markup = '<a id=" an id " class=" a class "></a>'\n soup = self.soup(markup)\n\n # Note that the spaces are stripped for 'class' but not for 'id'.\n a = soup.a\n assert " an id " == a["id"]\n assert ["a", "class"] == a["class"]\n\n # TreeBuilder takes an argument called 'multi_valued_attributes' which lets\n # you customize or disable this. As always, you can customize the TreeBuilder\n # by passing in a keyword argument to the BeautifulSoup constructor.\n soup = self.soup(markup, builder=default_builder, multi_valued_attributes=None)\n assert " a class " == soup.a["class"]\n\n # Here are two ways of saying that `id` is a multi-valued\n # attribute in this context, but 'class' is not.\n for switcheroo in ({"*": "id"}, {"a": "id"}):\n with warnings.catch_warnings(record=True):\n # This will create a warning about not explicitly\n # specifying a parser, but we'll ignore it.\n soup = self.soup(\n markup, builder=None, multi_valued_attributes=switcheroo\n )\n a = soup.a\n assert ["an", "id"] == a["id"]\n assert " a class " == a["class"]\n\n def test_replacement_classes(self):\n # Test the ability to pass in replacements for element classes\n # which will be used when building the tree.\n class TagPlus(Tag):\n pass\n\n class StringPlus(NavigableString):\n pass\n\n class CommentPlus(Comment):\n pass\n\n soup = self.soup(\n "<a><b>foo</b>bar</a><!--whee-->",\n element_classes={\n Tag: TagPlus,\n NavigableString: StringPlus,\n Comment: CommentPlus,\n },\n )\n\n # The tree was built with TagPlus, StringPlus, and CommentPlus objects,\n # rather than Tag, String, and Comment objects.\n assert all(\n isinstance(x, (TagPlus, StringPlus, CommentPlus)) for x in soup.descendants\n )\n\n def test_alternate_string_containers(self):\n # Test the ability to customize the string containers for\n # different types of tags.\n class PString(NavigableString):\n pass\n\n class BString(NavigableString):\n pass\n\n soup = self.soup(\n "<div>Hello.<p>Here is <b>some <i>bolded</i></b> text",\n string_containers={\n "b": BString,\n "p": PString,\n },\n )\n\n # The string before the <p> tag is a regular NavigableString.\n assert isinstance(soup.div.contents[0], NavigableString)\n\n # The string inside the <p> tag, but not inside the <i> tag,\n # is a PString.\n assert isinstance(soup.p.contents[0], PString)\n\n # Every string inside the <b> tag is a BString, even the one that\n # was also inside an <i> tag.\n for s in soup.b.strings:\n assert isinstance(s, BString)\n\n # Now that parsing was complete, the string_container_stack\n # (where this information was kept) has been cleared out.\n assert [] == soup.string_container_stack\n\n @pytest.mark.parametrize("bad_markup", [1, False, lambda x: False])\n def test_invalid_markup_type(self, bad_markup):\n with pytest.raises(TypeError) as exc_info:\n BeautifulSoup(bad_markup, "html.parser")\n assert (\n f"Incoming markup is of an invalid type: {bad_markup!r}. Markup must be a string, a bytestring, or an open filehandle."\n in str(exc_info.value)\n )\n\n\nclass TestOutput(SoupTest):\n @pytest.mark.parametrize(\n "eventual_encoding,actual_encoding",\n [\n ("utf-8", "utf-8"),\n ("utf-16", "utf-16"),\n ],\n )\n def test_decode_xml_declaration(self, eventual_encoding, actual_encoding):\n # Most of the time, calling decode() on an XML document will\n # give you a document declaration that mentions the encoding\n # you intend to use when encoding the document as a\n # bytestring.\n soup = self.soup("<tag></tag>")\n soup.is_xml = True\n assert (\n f'<?xml version="1.0" encoding="{actual_encoding}"?>\n<tag></tag>'\n == soup.decode(eventual_encoding=eventual_encoding)\n )\n\n @pytest.mark.parametrize(\n "eventual_encoding", [x for x in PYTHON_SPECIFIC_ENCODINGS] + [None]\n )\n def test_decode_xml_declaration_with_missing_or_python_internal_eventual_encoding(\n self, eventual_encoding\n ):\n # But if you pass a Python internal encoding into decode(), or\n # omit the eventual_encoding altogether, the document\n # declaration won't mention any particular encoding.\n soup = BeautifulSoup("<tag></tag>", "html.parser")\n soup.is_xml = True\n assert '<?xml version="1.0"?>\n<tag></tag>' == soup.decode(\n eventual_encoding=eventual_encoding\n )\n\n def test(self):\n # BeautifulSoup subclasses Tag and extends the decode() method.\n # Make sure the other Tag methods which call decode() call\n # it correctly.\n soup = self.soup("<tag></tag>")\n assert b"<tag></tag>" == soup.encode(encoding="utf-8")\n assert b"<tag></tag>" == soup.encode_contents(encoding="utf-8")\n assert "<tag></tag>" == soup.decode_contents()\n assert "<tag>\n</tag>\n" == soup.prettify()\n\n\nclass TestWarnings(SoupTest):\n # Note that some of the tests in this class create BeautifulSoup\n # objects directly rather than using self.soup(). That's\n # because SoupTest.soup is defined in a different file,\n # which will throw off the assertion in _assert_warning\n # that the code that triggered the warning is in the same\n # file as the test.\n\n def _assert_warning(\n self, warnings: Iterable[warnings.WarningMessage], cls: Type[Warning]\n ) -> warnings.WarningMessage:\n for w in warnings:\n if isinstance(w.message, cls):\n assert w.filename == __file__\n return w\n raise Exception("%s warning not found in %r" % (cls, warnings))\n\n def _assert_no_parser_specified(self, w: Iterable[warnings.WarningMessage]) -> None:\n warning = self._assert_warning(w, GuessedAtParserWarning)\n message = str(warning.message)\n assert message.startswith(GuessedAtParserWarning.MESSAGE[:60])\n\n def test_warning_if_no_parser_specified(self):\n with warnings.catch_warnings(record=True) as w:\n BeautifulSoup("<a><b></b></a>")\n self._assert_no_parser_specified(w)\n\n def test_warning_if_parser_specified_too_vague(self):\n with warnings.catch_warnings(record=True) as w:\n BeautifulSoup("<a><b></b></a>", "html")\n self._assert_no_parser_specified(w)\n\n def test_no_warning_if_explicit_parser_specified(self):\n with warnings.catch_warnings(record=True) as w:\n self.soup("<a><b></b></a>")\n assert [] == w\n\n def test_warning_if_strainer_filters_everything(self):\n strainer = SoupStrainer(name="a", string="b")\n with warnings.catch_warnings(record=True) as w:\n self.soup("<a><b></b></a>", parse_only=strainer)\n warning = self._assert_warning(w, UserWarning)\n msg = str(warning.message)\n assert msg.startswith("The given value for parse_only will exclude everything:")\n\n def test_parseOnlyThese_renamed_to_parse_only(self):\n with warnings.catch_warnings(record=True) as w:\n soup = BeautifulSoup(\n "<a><b></b></a>",\n "html.parser",\n parseOnlyThese=SoupStrainer("b"),\n )\n warning = self._assert_warning(w, DeprecationWarning)\n msg = str(warning.message)\n assert "parseOnlyThese" in msg\n assert "parse_only" in msg\n assert b"<b></b>" == soup.encode()\n\n def test_fromEncoding_renamed_to_from_encoding(self):\n with warnings.catch_warnings(record=True) as w:\n utf8 = b"\xc3\xa9"\n soup = BeautifulSoup(utf8, "html.parser", fromEncoding="utf8")\n warning = self._assert_warning(w, DeprecationWarning)\n msg = str(warning.message)\n assert "fromEncoding" in msg\n assert "from_encoding" in msg\n assert "utf8" == soup.original_encoding\n\n def test_unrecognized_keyword_argument(self):\n with pytest.raises(TypeError):\n self.soup("<a>", no_such_argument=True)\n\n @pytest.mark.parametrize(\n "markup",\n [\n "markup.html",\n "markup.htm",\n "markup.HTML",\n "markup.txt",\n "markup.xhtml",\n "markup.xml",\n "/home/user/file.txt",\n r"c:\user\file.html" r"\\server\share\path\file.XhTml",\n ],\n )\n def test_resembles_filename_warning(self, markup):\n # A warning is issued if the "markup" looks like the name of\n # an HTML or text file, or a full path to a file on disk.\n with warnings.catch_warnings(record=True) as w:\n BeautifulSoup(markup, "html.parser")\n warning = self._assert_warning(w, MarkupResemblesLocatorWarning)\n assert "looks more like a filename" in str(warning.message)\n\n @pytest.mark.parametrize(\n "markup",\n [\n "filename",\n "markuphtml",\n "markup.com",\n "",\n # Excluded due to an irrelevant file extension.\n "markup.js",\n "markup.jpg",\n "markup.markup",\n # Excluded due to the lack of any file extension.\n "/home/user/file",\n r"c:\user\file.html" r"\\server\share\path\file",\n # Excluded because of two consecutive slashes _and_ the\n # colon.\n "log message containing a url http://www.url.com/ right there.html",\n # Excluded for containing various characters or combinations\n # not usually found in filenames.\n "two consecutive spaces.html",\n "two//consecutive//slashes.html",\n "looks/like/a/filename/but/oops/theres/a#comment.html",\n "two\nlines.html",\n "contains?.html",\n "contains*.html",\n "contains#.html",\n "contains&.html",\n "contains;.html",\n "contains>.html",\n "contains<.html",\n "contains$.html",\n "contains|.html",\n "contains:.html",\n ":-at-the-front.html",\n ],\n )\n def test_resembles_filename_no_warning(self, markup):\n # The 'looks more like a filename' warning is not issued if\n # the markup looks like a bare string, a domain name, or a\n # file that's not an HTML file.\n with warnings.catch_warnings(record=True) as w:\n self.soup(markup)\n assert [] == w\n\n def test_url_warning_with_bytes_url(self):\n url = b"http://www.crummybytes.com/"\n with warnings.catch_warnings(record=True) as warning_list:\n BeautifulSoup(url, "html.parser")\n warning = self._assert_warning(warning_list, MarkupResemblesLocatorWarning)\n assert "looks more like a URL" in str(warning.message)\n assert url not in str(warning.message).encode("utf8")\n\n def test_url_warning_with_unicode_url(self):\n url = "http://www.crummyunicode.com/"\n with warnings.catch_warnings(record=True) as warning_list:\n # note - this url must differ from the bytes one otherwise\n # python's warnings system swallows the second warning\n BeautifulSoup(url, "html.parser")\n warning = self._assert_warning(warning_list, MarkupResemblesLocatorWarning)\n assert "looks more like a URL" in str(warning.message)\n assert url not in str(warning.message)\n\n def test_url_warning_with_bytes_and_space(self):\n # Here the markup contains something besides a URL, so no warning\n # is issued.\n with warnings.catch_warnings(record=True) as warning_list:\n self.soup(b"http://www.crummybytes.com/ is great")\n assert not any("looks more like a URL" in str(w.message) for w in warning_list)\n\n def test_url_warning_with_unicode_and_space(self):\n with warnings.catch_warnings(record=True) as warning_list:\n self.soup("http://www.crummyunicode.com/ is great")\n assert not any("looks more like a URL" in str(w.message) for w in warning_list)\n\n\nclass TestSelectiveParsing(SoupTest):\n def test_parse_with_soupstrainer(self):\n markup = "No<b>Yes</b><a>No<b>Yes <c>Yes</c></b>"\n strainer = SoupStrainer("b")\n soup = self.soup(markup, parse_only=strainer)\n assert soup.encode() == b"<b>Yes</b><b>Yes <c>Yes</c></b>"\n\n\nclass TestNewTag(SoupTest):\n """Test the BeautifulSoup.new_tag() method."""\n\n def test_new_tag(self):\n soup = self.soup("")\n new_tag = soup.new_tag("foo", string="txt", bar="baz", attrs={"name": "a name"})\n assert isinstance(new_tag, Tag)\n assert "foo" == new_tag.name\n assert new_tag.string == "txt"\n assert dict(bar="baz", name="a name") == new_tag.attrs\n assert None is new_tag.parent\n\n # string can be null\n new_tag = soup.new_tag("foo")\n assert None is new_tag.string\n new_tag = soup.new_tag("foo", string=None)\n assert None is new_tag.string\n\n # Or the empty string\n new_tag = soup.new_tag("foo", string="")\n assert "" == new_tag.string\n\n @pytest.mark.skipif(\n not LXML_PRESENT, reason="lxml not installed, cannot parse XML document"\n )\n def test_xml_tag_inherits_self_closing_rules_from_builder(self):\n xml_soup = BeautifulSoup("", "xml")\n xml_br = xml_soup.new_tag("br")\n xml_p = xml_soup.new_tag("p")\n\n # Both the <br> and <p> tag are empty-element, just because\n # they have no contents.\n assert b"<br/>" == xml_br.encode()\n assert b"<p/>" == xml_p.encode()\n\n def test_tag_inherits_self_closing_rules_from_builder(self):\n html_soup = BeautifulSoup("", "html.parser")\n html_br = html_soup.new_tag("br")\n html_p = html_soup.new_tag("p")\n\n # The HTML builder users HTML's rules about which tags are\n # empty-element tags, and the new tags reflect these rules.\n assert b"<br/>" == html_br.encode()\n assert b"<p></p>" == html_p.encode()\n\n\nclass TestNewString(SoupTest):\n """Test the BeautifulSoup.new_string() method."""\n\n def test_new_string_creates_navigablestring(self):\n soup = self.soup("")\n s = soup.new_string("foo")\n assert "foo" == s\n assert isinstance(s, NavigableString)\n\n def test_new_string_can_create_navigablestring_subclass(self):\n soup = self.soup("")\n s = soup.new_string("foo", Comment)\n assert "foo" == s\n assert isinstance(s, Comment)\n\n\nclass TestPickle(SoupTest):\n # Test our ability to pickle the BeautifulSoup object itself.\n\n def test_normal_pickle(self):\n soup = self.soup("<a>some markup</a>")\n pickled = pickle.dumps(soup)\n unpickled = pickle.loads(pickled)\n assert "some markup" == unpickled.a.string\n\n def test_pickle_with_no_builder(self):\n # We had a bug that prevented pickling from working if\n # the builder wasn't set.\n soup = self.soup("some markup")\n soup.builder = None\n pickled = pickle.dumps(soup)\n unpickled = pickle.loads(pickled)\n assert "some markup" == unpickled.string\n\n\nclass TestEncodingConversion(SoupTest):\n # Test Beautiful Soup's ability to decode and encode from various\n # encodings.\n\n def setup_method(self):\n self.unicode_data = '<html><head><meta charset="utf-8"/></head><body><foo>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</foo></body></html>'\n self.utf8_data = self.unicode_data.encode("utf-8")\n # Just so you know what it looks like.\n assert (\n self.utf8_data\n == b'<html><head><meta charset="utf-8"/></head><body><foo>Sacr\xc3\xa9 bleu!</foo></body></html>'\n )\n\n def test_ascii_in_unicode_out(self):\n # ASCII input is converted to Unicode. The original_encoding\n # attribute is set to 'utf-8', a superset of ASCII.\n chardet = dammit._chardet_dammit\n logging.disable(logging.WARNING)\n try:\n\n def noop(str):\n return None\n\n # Disable chardet, which will realize that the ASCII is ASCII.\n dammit._chardet_dammit = noop\n ascii = b"<foo>a</foo>"\n soup_from_ascii = self.soup(ascii)\n unicode_output = soup_from_ascii.decode()\n assert isinstance(unicode_output, str)\n assert unicode_output == self.document_for(ascii.decode())\n assert soup_from_ascii.original_encoding.lower() == "utf-8"\n finally:\n logging.disable(logging.NOTSET)\n dammit._chardet_dammit = chardet\n\n def test_unicode_in_unicode_out(self):\n # Unicode input is left alone. The original_encoding attribute\n # is not set.\n soup_from_unicode = self.soup(self.unicode_data)\n assert soup_from_unicode.decode() == self.unicode_data\n assert soup_from_unicode.foo.string == "Sacr\xe9 bleu!"\n assert soup_from_unicode.original_encoding is None\n\n def test_utf8_in_unicode_out(self):\n # UTF-8 input is converted to Unicode. The original_encoding\n # attribute is set.\n soup_from_utf8 = self.soup(self.utf8_data)\n assert soup_from_utf8.decode() == self.unicode_data\n assert soup_from_utf8.foo.string == "Sacr\xe9 bleu!"\n\n def test_utf8_out(self):\n # The internal data structures can be encoded as UTF-8.\n soup_from_unicode = self.soup(self.unicode_data)\n assert soup_from_unicode.encode("utf-8") == self.utf8_data\n
|
.venv\Lib\site-packages\bs4\tests\test_soup.py
|
test_soup.py
|
Python
| 22,669 | 0.95 | 0.16113 | 0.168932 |
vue-tools
| 341 |
2024-09-29T17:25:52.436386
|
BSD-3-Clause
| true |
a9b53b02b38550758a513d1131a01c74
|
import warnings\nfrom bs4.element import (\n Comment,\n NavigableString,\n)\nfrom . import SoupTest\n\n\nclass TestTag(SoupTest):\n """Test various methods of Tag which aren't so complicated they\n need their own classes.\n """\n\n def test__should_pretty_print(self):\n # Test the rules about when a tag should be pretty-printed.\n tag = self.soup("").new_tag("a_tag")\n\n # No list of whitespace-preserving tags -> pretty-print\n tag._preserve_whitespace_tags = None\n assert True is tag._should_pretty_print(0)\n\n # List exists but tag is not on the list -> pretty-print\n tag.preserve_whitespace_tags = ["some_other_tag"]\n assert True is tag._should_pretty_print(1)\n\n # Indent level is None -> don't pretty-print\n assert False is tag._should_pretty_print(None)\n\n # Tag is on the whitespace-preserving list -> don't pretty-print\n tag.preserve_whitespace_tags = ["some_other_tag", "a_tag"]\n assert False is tag._should_pretty_print(1)\n\n def test_len(self):\n """The length of a Tag is its number of children."""\n soup = self.soup("<top>1<b>2</b>3</top>")\n\n # The BeautifulSoup object itself contains one element: the\n # <top> tag.\n assert len(soup.contents) == 1\n assert len(soup) == 1\n\n # The <top> tag contains three elements: the text node "1", the\n # <b> tag, and the text node "3".\n assert len(soup.top) == 3\n assert len(soup.top.contents) == 3\n\n def test_member_access_invokes_find(self):\n """Accessing a Python member .foo invokes find('foo')"""\n soup = self.soup("<b><i></i></b>")\n assert soup.b == soup.find("b")\n assert soup.b.i == soup.find("b").find("i")\n assert soup.a is None\n\n def test_deprecated_member_access(self):\n soup = self.soup("<b><i></i></b>")\n with warnings.catch_warnings(record=True) as w:\n tag = soup.bTag\n assert soup.b == tag\n assert (\n '.bTag is deprecated, use .find("b") instead. If you really were looking for a tag called bTag, use .find("bTag")'\n == str(w[0].message)\n )\n\n def test_has_attr(self):\n """has_attr() checks for the presence of an attribute.\n\n Please note note: has_attr() is different from\n __in__. has_attr() checks the tag's attributes and __in__\n checks the tag's chidlren.\n """\n soup = self.soup("<foo attr='bar'>")\n assert soup.foo.has_attr("attr")\n assert not soup.foo.has_attr("attr2")\n\n def test_attributes_come_out_in_alphabetical_order(self):\n markup = '<b a="1" z="5" m="3" f="2" y="4"></b>'\n self.assertSoupEquals(markup, '<b a="1" f="2" m="3" y="4" z="5"></b>')\n\n def test_string(self):\n # A Tag that contains only a text node makes that node\n # available as .string.\n soup = self.soup("<b>foo</b>")\n assert soup.b.string == "foo"\n\n def test_empty_tag_has_no_string(self):\n # A Tag with no children has no .stirng.\n soup = self.soup("<b></b>")\n assert soup.b.string is None\n\n def test_tag_with_multiple_children_has_no_string(self):\n # A Tag with no children has no .string.\n soup = self.soup("<a>foo<b></b><b></b></b>")\n assert soup.b.string is None\n\n soup = self.soup("<a>foo<b></b>bar</b>")\n assert soup.b.string is None\n\n # Even if all the children are strings, due to trickery,\n # it won't work--but this would be a good optimization.\n soup = self.soup("<a>foo</b>")\n soup.a.insert(1, "bar")\n assert soup.a.string is None\n\n def test_tag_with_recursive_string_has_string(self):\n # A Tag with a single child which has a .string inherits that\n # .string.\n soup = self.soup("<a><b>foo</b></a>")\n assert soup.a.string == "foo"\n assert soup.string == "foo"\n\n def test_lack_of_string(self):\n """Only a Tag containing a single text node has a .string."""\n soup = self.soup("<b>f<i>e</i>o</b>")\n assert soup.b.string is None\n\n soup = self.soup("<b></b>")\n assert soup.b.string is None\n\n def test_all_text(self):\n """Tag.text and Tag.get_text(sep=u"") -> all child text, concatenated"""\n soup = self.soup("<a>a<b>r</b> <r> t </r></a>")\n assert soup.a.text == "ar t "\n assert soup.a.get_text(strip=True) == "art"\n assert soup.a.get_text(",") == "a,r, , t "\n assert soup.a.get_text(",", strip=True) == "a,r,t"\n\n def test_get_text_ignores_special_string_containers(self):\n soup = self.soup("foo<!--IGNORE-->bar")\n assert soup.get_text() == "foobar"\n\n assert soup.get_text(types=(NavigableString, Comment)) == "fooIGNOREbar"\n assert soup.get_text(types=None) == "fooIGNOREbar"\n\n soup = self.soup("foo<style>CSS</style><script>Javascript</script>bar")\n assert soup.get_text() == "foobar"\n\n def test_all_strings_ignores_special_string_containers(self):\n soup = self.soup("foo<!--IGNORE-->bar")\n assert ["foo", "bar"] == list(soup.strings)\n\n soup = self.soup("foo<style>CSS</style><script>Javascript</script>bar")\n assert ["foo", "bar"] == list(soup.strings)\n\n def test_string_methods_inside_special_string_container_tags(self):\n # Strings inside tags like <script> are generally ignored by\n # methods like get_text, because they're not what humans\n # consider 'text'. But if you call get_text on the <script>\n # tag itself, those strings _are_ considered to be 'text',\n # because there's nothing else you might be looking for.\n\n style = self.soup("<div>a<style>Some CSS</style></div>")\n template = self.soup(\n "<div>a<template><p>Templated <b>text</b>.</p><!--With a comment.--></template></div>"\n )\n script = self.soup("<div>a<script><!--a comment-->Some text</script></div>")\n\n assert style.div.get_text() == "a"\n assert list(style.div.strings) == ["a"]\n assert style.div.style.get_text() == "Some CSS"\n assert list(style.div.style.strings) == ["Some CSS"]\n\n # The comment is not picked up here. That's because it was\n # parsed into a Comment object, which is not considered\n # interesting by template.strings.\n assert template.div.get_text() == "a"\n assert list(template.div.strings) == ["a"]\n assert template.div.template.get_text() == "Templated text."\n assert list(template.div.template.strings) == ["Templated ", "text", "."]\n\n # The comment is included here, because it didn't get parsed\n # into a Comment object--it's part of the Script string.\n assert script.div.get_text() == "a"\n assert list(script.div.strings) == ["a"]\n assert script.div.script.get_text() == "<!--a comment-->Some text"\n assert list(script.div.script.strings) == ["<!--a comment-->Some text"]\n\n\nclass TestMultiValuedAttributes(SoupTest):\n """Test the behavior of multi-valued attributes like 'class'.\n\n The values of such attributes are always presented as lists.\n """\n\n def test_single_value_becomes_list(self):\n soup = self.soup("<a class='foo'>")\n assert ["foo"] == soup.a["class"]\n\n def test_multiple_values_becomes_list(self):\n soup = self.soup("<a class='foo bar'>")\n assert ["foo", "bar"] == soup.a["class"]\n\n def test_multiple_values_separated_by_weird_whitespace(self):\n soup = self.soup("<a class='foo\tbar\nbaz'>")\n assert ["foo", "bar", "baz"] == soup.a["class"]\n\n def test_attributes_joined_into_string_on_output(self):\n soup = self.soup("<a class='foo\tbar'>")\n assert b'<a class="foo bar"></a>' == soup.a.encode()\n\n def test_get_attribute_list(self):\n soup = self.soup("<a id='abc def'>")\n assert ["abc def"] == soup.a.get_attribute_list("id")\n assert [] == soup.a.get_attribute_list("no such attribute")\n\n def test_accept_charset(self):\n soup = self.soup('<form accept-charset="ISO-8859-1 UTF-8">')\n assert ["ISO-8859-1", "UTF-8"] == soup.form["accept-charset"]\n\n def test_cdata_attribute_applying_only_to_one_tag(self):\n data = '<a accept-charset="ISO-8859-1 UTF-8"></a>'\n soup = self.soup(data)\n # We saw in another test that accept-charset is a cdata-list\n # attribute for the <form> tag. But it's not a cdata-list\n # attribute for any other tag.\n assert "ISO-8859-1 UTF-8" == soup.a["accept-charset"]\n\n def test_customization(self):\n # It's possible to change which attributes of which tags\n # are treated as multi-valued attributes.\n #\n # Here, 'id' is a multi-valued attribute and 'class' is not.\n #\n # TODO: This code is in the builder and should be tested there.\n soup = self.soup(\n '<a class="foo" id="bar">', multi_valued_attributes={"*": "id"}\n )\n assert soup.a["class"] == "foo"\n assert soup.a["id"] == ["bar"]\n\n def test_hidden_tag_is_invisible(self):\n # Setting .hidden on a tag makes it invisible in output, but\n # leaves its contents visible.\n #\n # This is not a documented or supported feature of Beautiful\n # Soup (e.g. NavigableString doesn't support .hidden even\n # though it could), but some people use it and it's not\n # hurting anything to verify that it keeps working.\n #\n soup = self.soup('<div id="1"><span id="2">a string</span></div>')\n soup.span.hidden = True\n assert '<div id="1">a string</div>' == str(soup.div)\n
|
.venv\Lib\site-packages\bs4\tests\test_tag.py
|
test_tag.py
|
Python
| 9,690 | 0.95 | 0.195021 | 0.225641 |
react-lib
| 493 |
2024-02-21T03:15:03.687543
|
Apache-2.0
| true |
6d783674ac754c90f3c474114174da4e
|
<css
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-4670634698080256.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-4670634698080256.testcase
|
Other
| 15 | 0.5 | 0.1 | 0 |
node-utils
| 61 |
2023-07-12T19:15:47.793427
|
MIT
| true |
fca200c31a56d801c21fb7c94f899d8a
|
<!DOCTyPEV PUBLIC''''
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-4818336571064320.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-4818336571064320.testcase
|
Other
| 23 | 0.5 | 0.1 | 0 |
vue-tools
| 873 |
2025-07-07T21:25:02.707611
|
MIT
| true |
84e05a31387b8db7629bc95c4ffda834
|
)<a><math><TR><a><mI><a><p><a>
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-4999465949331456.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-4999465949331456.testcase
|
Other
| 30 | 0.5 | 0.1 | 0 |
awesome-app
| 309 |
2023-07-12T01:02:56.922493
|
BSD-3-Clause
| true |
6470f115c164cd55b0de6141a65ba85c
|
- <s/><ht<!charset=utf<t>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><\n<html ,j n/ 0//
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-5000587759190016.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-5000587759190016.testcase
|
Other
| 15,347 | 0.8 | 0 | 0 |
vue-tools
| 947 |
2025-04-19T02:03:14.545897
|
Apache-2.0
| true |
bfd11ecc7dc12473d101c58d499095ff
|
<s
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-5167584867909632.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-5167584867909632.testcase
|
Other
| 19,469 | 0.8 | 0 | 0 |
vue-tools
| 784 |
2025-01-11T18:09:14.598886
|
BSD-3-Clause
| true |
c201403489628d0842715525bef2099f
|
<r/D='
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-5270998950477824.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-5270998950477824.testcase
|
Other
| 12 | 0.5 | 0.1 | 0 |
python-kit
| 830 |
2023-07-10T20:28:04.685419
|
GPL-3.0
| true |
828458f62f0cfffb011d94980ffd5a20
|
><applet></applet><applet></applet><apple|><applet><applet><appl><applet><applet></applet></applet></applet></applet><applet></applet><apple>t<applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet>et><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><azplet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><plet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet><applet></applet></applet></applet></applet></appt></applet></applet></applet></applet></applet></applet></applet></applet></applet></applet></applet></applet></applet></applet></applet></applet></applet></applet><<meta charset=utf-8>
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-5375146639360000.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-5375146639360000.testcase
|
Other
| 4,317 | 0.7 | 0.1 | 0 |
awesome-app
| 193 |
2023-11-22T22:34:34.200136
|
Apache-2.0
| true |
2e4b4aeae31f2ac289d7901c68314208
|
O\nS<q\nT><v="quiv="Content-Type"content=gha--
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-5492400320282624.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-5492400320282624.testcase
|
Other
| 11,502 | 0.8 | 0 | 0 |
react-lib
| 821 |
2024-11-09T20:00:41.747206
|
BSD-3-Clause
| true |
690a3453e8d3a86e03e1b641cdae2c51
|
\n<![
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-5703933063462912.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-5703933063462912.testcase
|
Other
| 5 | 0.5 | 0 | 0 |
vue-tools
| 529 |
2023-12-04T05:57:07.265143
|
Apache-2.0
| true |
09ae0c7749551545232df0ed22f208f9
|
-<math><sElect><mi><sElect><sElect>
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-5843991618256896.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-5843991618256896.testcase
|
Other
| 35 | 0.5 | 0.1 | 0 |
awesome-app
| 135 |
2023-12-31T18:59:35.826958
|
BSD-3-Clause
| true |
1e7c84252ccc327e2792f691c56744ee
|
:fontipt><!--</script><script><pt><script<>!--</script6<<head/Xpe" charse/
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-5984173902397440.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-5984173902397440.testcase
|
Other
| 51,495 | 0.8 | 0 | 0 |
react-lib
| 843 |
2024-12-14T23:48:51.034834
|
GPL-3.0
| true |
382638df193384d3a4b50614ba91be1a
|
)<math><math><math><math><math><math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&)<math><math><annotation-xul>&
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-6124268085182464.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-6124268085182464.testcase
|
Other
| 10,380 | 0.7 | 0.1 | 0 |
react-lib
| 629 |
2024-09-16T01:26:57.396909
|
Apache-2.0
| true |
c5527d0160f8af49a19b7b0065f5a7bf
|
<table><svg><html>
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-6241471367348224.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-6241471367348224.testcase
|
Other
| 19 | 0.5 | 0.1 | 0 |
python-kit
| 246 |
2023-12-11T08:29:05.927693
|
GPL-3.0
| true |
5639f6ee4abb90155d952ad864172cb9
|
- <math><select><mi><select><select>t
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-6306874195312640.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-6306874195312640.testcase
|
Other
| 47 | 0.5 | 0.1 | 0 |
react-lib
| 60 |
2023-10-21T22:33:20.006455
|
GPL-3.0
| true |
487f66b8794b4ca818b9c1c6511bc056
|
)<math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><math><annOtatiop
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-6450958476902400.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-6450958476902400.testcase
|
Other
| 3,546 | 0.7 | 0.1 | 0 |
node-utils
| 209 |
2024-02-02T15:22:35.112913
|
Apache-2.0
| true |
8408a78f5ba83bc150eb6d5280141361
|
<TABLE><<!>;<!><<!>.<lec><th>i><a><mat
|
.venv\Lib\site-packages\bs4\tests\fuzz\clusterfuzz-testcase-minimized-bs4_fuzzer-6600557255327744.testcase
|
clusterfuzz-testcase-minimized-bs4_fuzzer-6600557255327744.testcase
|
Other
| 124 | 0.7 | 0.1 | 0 |
awesome-app
| 158 |
2024-09-12T06:58:50.790816
|
MIT
| true |
9533158de6d495cdd394b03e6a537dfc
|
Q<a href=="1" b="10" a="2" a="3" a="4">Multiple values for the same attri=ute.</b>\n<div><tabble</td></tr></table></div>\n<div><tablee id="3"><tr><td>foo</td></tr></table or XM:<table id="2"><tr><td>f<oo/td></tr></table></ble id="1"><tr><tdd of
|
.venv\Lib\site-packages\bs4\tests\fuzz\crash-0d306a50c8ed8bcd0785b67000fcd5dea1d33f08.testcase
|
crash-0d306a50c8ed8bcd0785b67000fcd5dea1d33f08.testcase
|
Other
| 2,607 | 0.7 | 0.076923 | 0 |
awesome-app
| 956 |
2024-12-04T09:32:44.473654
|
MIT
| true |
6e7c04daf2d8b791a784f03dff48f46d
|
Z
|
.venv\Lib\site-packages\bs4\tests\fuzz\crash-ffbdfa8a2b26f13537b68d3794b0478a4090ee4a.testcase
|
crash-ffbdfa8a2b26f13537b68d3794b0478a4090ee4a.testcase
|
Other
| 103 | 0.5 | 0 | 0 |
react-lib
| 397 |
2024-02-19T02:36:29.244367
|
MIT
| true |
85678aa28e1340a932ea57031284ad85
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_builder.cpython-313.pyc
|
test_builder.cpython-313.pyc
|
Other
| 1,660 | 0.8 | 0 | 0 |
awesome-app
| 411 |
2024-11-28T05:25:16.949930
|
Apache-2.0
| true |
22893913fd6416eb62f3f38b4e1e6821
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_builder_registry.cpython-313.pyc
|
test_builder_registry.cpython-313.pyc
|
Other
| 7,841 | 0.95 | 0.017857 | 0 |
node-utils
| 20 |
2024-03-18T14:53:40.870142
|
MIT
| true |
4fd7b09b0af2a998c9ff1509e8fa69c9
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_css.cpython-313.pyc
|
test_css.cpython-313.pyc
|
Other
| 29,061 | 0.95 | 0.066038 | 0.009934 |
vue-tools
| 196 |
2023-10-25T13:26:41.649093
|
MIT
| true |
27c17937a38cd8de9f0ea7be55c4f747
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_dammit.cpython-313.pyc
|
test_dammit.cpython-313.pyc
|
Other
| 19,964 | 0.95 | 0.00885 | 0 |
python-kit
| 491 |
2024-10-09T19:59:35.421629
|
MIT
| true |
6c531a5992e51565c82118b04d670d77
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_element.cpython-313.pyc
|
test_element.cpython-313.pyc
|
Other
| 6,216 | 0.8 | 0 | 0.054054 |
vue-tools
| 449 |
2024-04-26T04:02:21.693154
|
MIT
| true |
12c6de8569306b5f706ed5a6fbf5a6aa
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_filter.cpython-313.pyc
|
test_filter.cpython-313.pyc
|
Other
| 32,467 | 0.95 | 0.040462 | 0.003003 |
vue-tools
| 911 |
2025-04-24T10:24:27.918451
|
BSD-3-Clause
| true |
76080f2ba53fd8702110a8306316c095
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_formatter.cpython-313.pyc
|
test_formatter.cpython-313.pyc
|
Other
| 7,810 | 0.8 | 0 | 0.010753 |
node-utils
| 560 |
2025-01-16T21:18:34.486108
|
MIT
| true |
2144a39833c3950e7f1f830d03ca5544
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_fuzz.cpython-313.pyc
|
test_fuzz.cpython-313.pyc
|
Other
| 7,111 | 0.95 | 0.015873 | 0 |
python-kit
| 66 |
2023-11-08T21:34:09.961196
|
MIT
| true |
8af136046e7f9b15a87e0171ad935a37
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_html5lib.cpython-313.pyc
|
test_html5lib.cpython-313.pyc
|
Other
| 11,944 | 0.8 | 0.015385 | 0 |
vue-tools
| 408 |
2023-12-13T10:14:21.379469
|
Apache-2.0
| true |
5e1d4b753b7156c399713675cd8a7388
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_htmlparser.cpython-313.pyc
|
test_htmlparser.cpython-313.pyc
|
Other
| 7,351 | 0.8 | 0.037736 | 0 |
node-utils
| 746 |
2024-03-03T13:29:22.717539
|
MIT
| true |
c2de349261391b1c1fe8243df67eb94c
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_lxml.cpython-313.pyc
|
test_lxml.cpython-313.pyc
|
Other
| 8,276 | 0.95 | 0.024096 | 0 |
awesome-app
| 62 |
2024-05-25T13:24:23.198322
|
Apache-2.0
| true |
33ffdbdb27d434cba5aa6dd5f1e28dcb
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_navigablestring.cpython-313.pyc
|
test_navigablestring.cpython-313.pyc
|
Other
| 8,695 | 0.8 | 0 | 0.041096 |
awesome-app
| 916 |
2025-03-05T16:35:23.690157
|
Apache-2.0
| true |
d9153e97f76c55fe30cc29c4306c6dfe
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_pageelement.cpython-313.pyc
|
test_pageelement.cpython-313.pyc
|
Other
| 23,059 | 0.95 | 0.032967 | 0.011364 |
vue-tools
| 643 |
2023-11-16T22:49:38.048362
|
MIT
| true |
bf7cfb2dd94308d9ad45caef9ca659c6
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_soup.cpython-313.pyc
|
test_soup.cpython-313.pyc
|
Other
| 32,176 | 0.95 | 0.018182 | 0.018315 |
awesome-app
| 405 |
2023-10-16T02:49:45.528733
|
Apache-2.0
| true |
b82843f6f5053d3a182e18e2be068b8f
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_tag.cpython-313.pyc
|
test_tag.cpython-313.pyc
|
Other
| 14,264 | 0.8 | 0.24 | 0 |
python-kit
| 480 |
2025-05-02T13:37:33.113731
|
BSD-3-Clause
| true |
7a078ba63de2950778649fa1b66b2321
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\test_tree.cpython-313.pyc
|
test_tree.cpython-313.pyc
|
Other
| 94,386 | 0.75 | 0.028213 | 0.001715 |
python-kit
| 104 |
2023-09-21T21:02:57.525294
|
BSD-3-Clause
| true |
7bb6321e646255fb6846acecc76c0dd9
|
\n\n
|
.venv\Lib\site-packages\bs4\tests\__pycache__\__init__.cpython-313.pyc
|
__init__.cpython-313.pyc
|
Other
| 68,569 | 0.75 | 0.039911 | 0 |
vue-tools
| 190 |
2025-03-17T19:57:34.697277
|
BSD-3-Clause
| true |
45e487bd602bb86188c3edafb7a92744
|
\n\n
|
.venv\Lib\site-packages\bs4\__pycache__\css.cpython-313.pyc
|
css.cpython-313.pyc
|
Other
| 13,540 | 0.95 | 0.089041 | 0.008439 |
node-utils
| 408 |
2023-12-28T11:39:08.902351
|
Apache-2.0
| false |
23fbc46a2492683b120ad7fc4d1eef52
|
\n\n
|
.venv\Lib\site-packages\bs4\__pycache__\dammit.cpython-313.pyc
|
dammit.cpython-313.pyc
|
Other
| 45,694 | 0.95 | 0.044234 | 0 |
react-lib
| 308 |
2025-05-11T07:13:30.981005
|
GPL-3.0
| false |
27488ba0907a969caae349234b45b984
|
\n\n
|
.venv\Lib\site-packages\bs4\__pycache__\diagnose.cpython-313.pyc
|
diagnose.cpython-313.pyc
|
Other
| 12,767 | 0.95 | 0.02439 | 0.009009 |
vue-tools
| 45 |
2024-01-26T16:06:19.347118
|
MIT
| false |
c3c9ccfed9a8c4ba953009924919fe21
|
\n\n
|
.venv\Lib\site-packages\bs4\__pycache__\element.cpython-313.pyc
|
element.cpython-313.pyc
|
Other
| 105,596 | 0.75 | 0.073994 | 0.002467 |
react-lib
| 753 |
2023-12-21T23:16:25.955957
|
GPL-3.0
| false |
f624ac63fde590f987aaa54b187fb081
|
\n\n
|
.venv\Lib\site-packages\bs4\__pycache__\exceptions.cpython-313.pyc
|
exceptions.cpython-313.pyc
|
Other
| 1,855 | 0.8 | 0.095238 | 0 |
node-utils
| 158 |
2024-12-26T08:35:54.952508
|
GPL-3.0
| false |
7155a52d92aeee92ab6165c926056309
|
\n\n
|
.venv\Lib\site-packages\bs4\__pycache__\filter.cpython-313.pyc
|
filter.cpython-313.pyc
|
Other
| 28,660 | 0.95 | 0.107784 | 0.003497 |
react-lib
| 17 |
2023-08-30T15:26:02.518534
|
Apache-2.0
| false |
cced5d295a0d40a02da6a0d04e777822
|
\n\n
|
.venv\Lib\site-packages\bs4\__pycache__\formatter.cpython-313.pyc
|
formatter.cpython-313.pyc
|
Other
| 10,202 | 0.95 | 0.047904 | 0.059211 |
python-kit
| 60 |
2024-01-03T06:32:18.419770
|
BSD-3-Clause
| false |
6de317c21846b5a37a71600767148feb
|
\n\n
|
.venv\Lib\site-packages\bs4\__pycache__\_deprecation.cpython-313.pyc
|
_deprecation.cpython-313.pyc
|
Other
| 3,744 | 0.95 | 0.1 | 0 |
react-lib
| 3 |
2024-02-08T22:26:38.260767
|
BSD-3-Clause
| false |
7dc6bb887ead1a604ef5b1e3a702c2ab
|
\n\n
|
.venv\Lib\site-packages\bs4\__pycache__\_typing.cpython-313.pyc
|
_typing.cpython-313.pyc
|
Other
| 3,610 | 0.8 | 0 | 0 |
vue-tools
| 23 |
2024-06-04T19:26:10.959489
|
Apache-2.0
| false |
82f392aa27fe16cb8ee9e1081f154b98
|
\n\n
|
.venv\Lib\site-packages\bs4\__pycache__\_warnings.cpython-313.pyc
|
_warnings.cpython-313.pyc
|
Other
| 5,673 | 0.95 | 0.083333 | 0 |
vue-tools
| 512 |
2024-01-12T07:39:27.539895
|
Apache-2.0
| false |
4a3a89f99878cc772212250ab8caa4d9
|
\n\n
|
.venv\Lib\site-packages\bs4\__pycache__\__init__.cpython-313.pyc
|
__init__.cpython-313.pyc
|
Other
| 39,312 | 0.95 | 0.072692 | 0.01573 |
react-lib
| 493 |
2024-12-28T08:35:42.153726
|
GPL-3.0
| false |
651df78b0ba501ac3fcb7c7b41494be2
|
"""\ncertifi.py\n~~~~~~~~~~\n\nThis module returns the installation location of cacert.pem or its contents.\n"""\nimport sys\nimport atexit\n\ndef exit_cacert_ctx() -> None:\n _CACERT_CTX.__exit__(None, None, None) # type: ignore[union-attr]\n\n\nif sys.version_info >= (3, 11):\n\n from importlib.resources import as_file, files\n\n _CACERT_CTX = None\n _CACERT_PATH = None\n\n def where() -> str:\n # This is slightly terrible, but we want to delay extracting the file\n # in cases where we're inside of a zipimport situation until someone\n # actually calls where(), but we don't want to re-extract the file\n # on every call of where(), so we'll do it once then store it in a\n # global variable.\n global _CACERT_CTX\n global _CACERT_PATH\n if _CACERT_PATH is None:\n # This is slightly janky, the importlib.resources API wants you to\n # manage the cleanup of this file, so it doesn't actually return a\n # path, it returns a context manager that will give you the path\n # when you enter it and will do any cleanup when you leave it. In\n # the common case of not needing a temporary file, it will just\n # return the file system location and the __exit__() is a no-op.\n #\n # We also have to hold onto the actual context manager, because\n # it will do the cleanup whenever it gets garbage collected, so\n # we will also store that at the global level as well.\n _CACERT_CTX = as_file(files("certifi").joinpath("cacert.pem"))\n _CACERT_PATH = str(_CACERT_CTX.__enter__())\n atexit.register(exit_cacert_ctx)\n\n return _CACERT_PATH\n\n def contents() -> str:\n return files("certifi").joinpath("cacert.pem").read_text(encoding="ascii")\n\nelse:\n\n from importlib.resources import path as get_path, read_text\n\n _CACERT_CTX = None\n _CACERT_PATH = None\n\n def where() -> str:\n # This is slightly terrible, but we want to delay extracting the\n # file in cases where we're inside of a zipimport situation until\n # someone actually calls where(), but we don't want to re-extract\n # the file on every call of where(), so we'll do it once then store\n # it in a global variable.\n global _CACERT_CTX\n global _CACERT_PATH\n if _CACERT_PATH is None:\n # This is slightly janky, the importlib.resources API wants you\n # to manage the cleanup of this file, so it doesn't actually\n # return a path, it returns a context manager that will give\n # you the path when you enter it and will do any cleanup when\n # you leave it. In the common case of not needing a temporary\n # file, it will just return the file system location and the\n # __exit__() is a no-op.\n #\n # We also have to hold onto the actual context manager, because\n # it will do the cleanup whenever it gets garbage collected, so\n # we will also store that at the global level as well.\n _CACERT_CTX = get_path("certifi", "cacert.pem")\n _CACERT_PATH = str(_CACERT_CTX.__enter__())\n atexit.register(exit_cacert_ctx)\n\n return _CACERT_PATH\n\n def contents() -> str:\n return read_text("certifi", "cacert.pem", encoding="ascii")\n
|
.venv\Lib\site-packages\certifi\core.py
|
core.py
|
Python
| 3,394 | 0.95 | 0.096386 | 0.455882 |
node-utils
| 100 |
2025-01-06T18:20:20.707000
|
BSD-3-Clause
| false |
77567a68e36469b2c2550db9fcc3c2a9
|
from .core import contents, where\n\n__all__ = ["contents", "where"]\n__version__ = "2025.06.15"\n
|
.venv\Lib\site-packages\certifi\__init__.py
|
__init__.py
|
Python
| 94 | 0.65 | 0 | 0 |
vue-tools
| 835 |
2025-01-15T07:25:22.351916
|
Apache-2.0
| false |
9db2e68db24503c357e3bbf458c70076
|
import argparse\n\nfrom certifi import contents, where\n\nparser = argparse.ArgumentParser()\nparser.add_argument("-c", "--contents", action="store_true")\nargs = parser.parse_args()\n\nif args.contents:\n print(contents())\nelse:\n print(where())\n
|
.venv\Lib\site-packages\certifi\__main__.py
|
__main__.py
|
Python
| 243 | 0.85 | 0.083333 | 0 |
vue-tools
| 282 |
2025-04-15T05:05:42.213202
|
Apache-2.0
| false |
269e7f0ca2fa570b10e690595e6aedab
|
\n\n
|
.venv\Lib\site-packages\certifi\__pycache__\core.cpython-313.pyc
|
core.cpython-313.pyc
|
Other
| 2,064 | 0.95 | 0 | 0 |
react-lib
| 658 |
2024-03-30T00:59:06.984921
|
BSD-3-Clause
| false |
b9e087ab28a867a20fb41cc005fb7837
|
\n\n
|
.venv\Lib\site-packages\certifi\__pycache__\__init__.cpython-313.pyc
|
__init__.cpython-313.pyc
|
Other
| 309 | 0.7 | 0 | 0 |
react-lib
| 241 |
2024-01-26T08:35:52.380335
|
Apache-2.0
| false |
cf7b2f21f7c6af2e56d524dae17a3dcf
|
\n\n
|
.venv\Lib\site-packages\certifi\__pycache__\__main__.cpython-313.pyc
|
__main__.cpython-313.pyc
|
Other
| 626 | 0.8 | 0 | 0 |
python-kit
| 615 |
2025-05-31T14:45:37.001047
|
Apache-2.0
| false |
f4f51d91a08bd1e8ff1b27ce45452b1f
|
pip\n
|
.venv\Lib\site-packages\certifi-2025.6.15.dist-info\INSTALLER
|
INSTALLER
|
Other
| 4 | 0.5 | 0 | 0 |
vue-tools
| 188 |
2024-12-23T14:49:41.440106
|
Apache-2.0
| false |
365c9bfeb7d89244f2ce01c1de44cb85
|
Metadata-Version: 2.4\nName: certifi\nVersion: 2025.6.15\nSummary: Python package for providing Mozilla's CA Bundle.\nHome-page: https://github.com/certifi/python-certifi\nAuthor: Kenneth Reitz\nAuthor-email: me@kennethreitz.com\nLicense: MPL-2.0\nProject-URL: Source, https://github.com/certifi/python-certifi\nClassifier: Development Status :: 5 - Production/Stable\nClassifier: Intended Audience :: Developers\nClassifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)\nClassifier: Natural Language :: English\nClassifier: Programming Language :: Python\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3 :: Only\nClassifier: Programming Language :: Python :: 3.7\nClassifier: Programming Language :: Python :: 3.8\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Programming Language :: Python :: 3.12\nClassifier: Programming Language :: Python :: 3.13\nRequires-Python: >=3.7\nLicense-File: LICENSE\nDynamic: author\nDynamic: author-email\nDynamic: classifier\nDynamic: description\nDynamic: home-page\nDynamic: license\nDynamic: license-file\nDynamic: project-url\nDynamic: requires-python\nDynamic: summary\n\nCertifi: Python SSL Certificates\n================================\n\nCertifi provides Mozilla's carefully curated collection of Root Certificates for\nvalidating the trustworthiness of SSL certificates while verifying the identity\nof TLS hosts. It has been extracted from the `Requests`_ project.\n\nInstallation\n------------\n\n``certifi`` is available on PyPI. Simply install it with ``pip``::\n\n $ pip install certifi\n\nUsage\n-----\n\nTo reference the installed certificate authority (CA) bundle, you can use the\nbuilt-in function::\n\n >>> import certifi\n\n >>> certifi.where()\n '/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'\n\nOr from the command line::\n\n $ python -m certifi\n /usr/local/lib/python3.7/site-packages/certifi/cacert.pem\n\nEnjoy!\n\n.. _`Requests`: https://requests.readthedocs.io/en/master/\n\nAddition/Removal of Certificates\n--------------------------------\n\nCertifi does not support any addition/removal or other modification of the\nCA trust store content. This project is intended to provide a reliable and\nhighly portable root of trust to python deployments. Look to upstream projects\nfor methods to use alternate trust.\n
|
.venv\Lib\site-packages\certifi-2025.6.15.dist-info\METADATA
|
METADATA
|
Other
| 2,423 | 0.95 | 0.064935 | 0 |
vue-tools
| 340 |
2024-09-24T08:37:12.899247
|
MIT
| false |
ab7244efeff4d37ad438ac16d369abac
|
certifi-2025.6.15.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\ncertifi-2025.6.15.dist-info/METADATA,sha256=zgiNbFi9bMv8olVT9OQxB7G5-xQmCjQZ5eO7Z0IGKoI,2423\ncertifi-2025.6.15.dist-info/RECORD,,\ncertifi-2025.6.15.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91\ncertifi-2025.6.15.dist-info/licenses/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989\ncertifi-2025.6.15.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8\ncertifi/__init__.py,sha256=H8ta5ryBBsJrzYoTklAyzrzsu-dZlfkyL5_aPq5vvFM,94\ncertifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243\ncertifi/__pycache__/__init__.cpython-313.pyc,,\ncertifi/__pycache__/__main__.cpython-313.pyc,,\ncertifi/__pycache__/core.cpython-313.pyc,,\ncertifi/cacert.pem,sha256=sc3S1mV1jvSdCPQOoT4agm5fBBLp4JQMkh7RAhRkzcI,281225\ncertifi/core.py,sha256=XFXycndG5pf37ayeF8N32HUuDafsyhkVMbO4BAPWHa0,3394\ncertifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\n
|
.venv\Lib\site-packages\certifi-2025.6.15.dist-info\RECORD
|
RECORD
|
Other
| 1,023 | 0.7 | 0 | 0 |
node-utils
| 868 |
2025-04-27T11:30:43.803085
|
Apache-2.0
| false |
3736ffe512cfc227b8f53d804c63b1a5
|
certifi\n
|
.venv\Lib\site-packages\certifi-2025.6.15.dist-info\top_level.txt
|
top_level.txt
|
Other
| 8 | 0.5 | 0 | 0 |
awesome-app
| 816 |
2024-07-18T05:44:31.898377
|
MIT
| false |
5ebd7f7c387ebb31c14e3c701023ac97
|
Wheel-Version: 1.0\nGenerator: setuptools (80.9.0)\nRoot-Is-Purelib: true\nTag: py3-none-any\n\n
|
.venv\Lib\site-packages\certifi-2025.6.15.dist-info\WHEEL
|
WHEEL
|
Other
| 91 | 0.5 | 0 | 0 |
node-utils
| 768 |
2023-08-25T14:36:28.628374
|
MIT
| false |
08dd01ac2afdbb287cc668d51c7056c8
|
This package contains a modified version of ca-bundle.crt:\n\nca-bundle.crt -- Bundle of CA Root Certificates\n\nThis is a bundle of X.509 certificates of public Certificate Authorities\n(CA). These were automatically extracted from Mozilla's root certificates\nfile (certdata.txt). This file can be found in the mozilla source tree:\nhttps://hg.mozilla.org/mozilla-central/file/tip/security/nss/lib/ckfw/builtins/certdata.txt\nIt contains the certificates in PEM format and therefore\ncan be directly used with curl / libcurl / php_curl, or with\nan Apache+mod_ssl webserver for SSL client authentication.\nJust configure this file as the SSLCACertificateFile.#\n\n***** BEGIN LICENSE BLOCK *****\nThis Source Code Form is subject to the terms of the Mozilla Public License,\nv. 2.0. If a copy of the MPL was not distributed with this file, You can obtain\none at http://mozilla.org/MPL/2.0/.\n\n***** END LICENSE BLOCK *****\n@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $\n
|
.venv\Lib\site-packages\certifi-2025.6.15.dist-info\licenses\LICENSE
|
LICENSE
|
Other
| 989 | 0.8 | 0.05 | 0.125 |
awesome-app
| 377 |
2024-08-11T06:17:12.289696
|
MIT
| false |
11618cb6a975948679286b1211bd573c
|
from .error import VerificationError\n\nclass CffiOp(object):\n def __init__(self, op, arg):\n self.op = op\n self.arg = arg\n\n def as_c_expr(self):\n if self.op is None:\n assert isinstance(self.arg, str)\n return '(_cffi_opcode_t)(%s)' % (self.arg,)\n classname = CLASS_NAME[self.op]\n return '_CFFI_OP(_CFFI_OP_%s, %s)' % (classname, self.arg)\n\n def as_python_bytes(self):\n if self.op is None and self.arg.isdigit():\n value = int(self.arg) # non-negative: '-' not in self.arg\n if value >= 2**31:\n raise OverflowError("cannot emit %r: limited to 2**31-1"\n % (self.arg,))\n return format_four_bytes(value)\n if isinstance(self.arg, str):\n raise VerificationError("cannot emit to Python: %r" % (self.arg,))\n return format_four_bytes((self.arg << 8) | self.op)\n\n def __str__(self):\n classname = CLASS_NAME.get(self.op, self.op)\n return '(%s %s)' % (classname, self.arg)\n\ndef format_four_bytes(num):\n return '\\x%02X\\x%02X\\x%02X\\x%02X' % (\n (num >> 24) & 0xFF,\n (num >> 16) & 0xFF,\n (num >> 8) & 0xFF,\n (num ) & 0xFF)\n\nOP_PRIMITIVE = 1\nOP_POINTER = 3\nOP_ARRAY = 5\nOP_OPEN_ARRAY = 7\nOP_STRUCT_UNION = 9\nOP_ENUM = 11\nOP_FUNCTION = 13\nOP_FUNCTION_END = 15\nOP_NOOP = 17\nOP_BITFIELD = 19\nOP_TYPENAME = 21\nOP_CPYTHON_BLTN_V = 23 # varargs\nOP_CPYTHON_BLTN_N = 25 # noargs\nOP_CPYTHON_BLTN_O = 27 # O (i.e. a single arg)\nOP_CONSTANT = 29\nOP_CONSTANT_INT = 31\nOP_GLOBAL_VAR = 33\nOP_DLOPEN_FUNC = 35\nOP_DLOPEN_CONST = 37\nOP_GLOBAL_VAR_F = 39\nOP_EXTERN_PYTHON = 41\n\nPRIM_VOID = 0\nPRIM_BOOL = 1\nPRIM_CHAR = 2\nPRIM_SCHAR = 3\nPRIM_UCHAR = 4\nPRIM_SHORT = 5\nPRIM_USHORT = 6\nPRIM_INT = 7\nPRIM_UINT = 8\nPRIM_LONG = 9\nPRIM_ULONG = 10\nPRIM_LONGLONG = 11\nPRIM_ULONGLONG = 12\nPRIM_FLOAT = 13\nPRIM_DOUBLE = 14\nPRIM_LONGDOUBLE = 15\n\nPRIM_WCHAR = 16\nPRIM_INT8 = 17\nPRIM_UINT8 = 18\nPRIM_INT16 = 19\nPRIM_UINT16 = 20\nPRIM_INT32 = 21\nPRIM_UINT32 = 22\nPRIM_INT64 = 23\nPRIM_UINT64 = 24\nPRIM_INTPTR = 25\nPRIM_UINTPTR = 26\nPRIM_PTRDIFF = 27\nPRIM_SIZE = 28\nPRIM_SSIZE = 29\nPRIM_INT_LEAST8 = 30\nPRIM_UINT_LEAST8 = 31\nPRIM_INT_LEAST16 = 32\nPRIM_UINT_LEAST16 = 33\nPRIM_INT_LEAST32 = 34\nPRIM_UINT_LEAST32 = 35\nPRIM_INT_LEAST64 = 36\nPRIM_UINT_LEAST64 = 37\nPRIM_INT_FAST8 = 38\nPRIM_UINT_FAST8 = 39\nPRIM_INT_FAST16 = 40\nPRIM_UINT_FAST16 = 41\nPRIM_INT_FAST32 = 42\nPRIM_UINT_FAST32 = 43\nPRIM_INT_FAST64 = 44\nPRIM_UINT_FAST64 = 45\nPRIM_INTMAX = 46\nPRIM_UINTMAX = 47\nPRIM_FLOATCOMPLEX = 48\nPRIM_DOUBLECOMPLEX = 49\nPRIM_CHAR16 = 50\nPRIM_CHAR32 = 51\n\n_NUM_PRIM = 52\n_UNKNOWN_PRIM = -1\n_UNKNOWN_FLOAT_PRIM = -2\n_UNKNOWN_LONG_DOUBLE = -3\n\n_IO_FILE_STRUCT = -1\n\nPRIMITIVE_TO_INDEX = {\n 'char': PRIM_CHAR,\n 'short': PRIM_SHORT,\n 'int': PRIM_INT,\n 'long': PRIM_LONG,\n 'long long': PRIM_LONGLONG,\n 'signed char': PRIM_SCHAR,\n 'unsigned char': PRIM_UCHAR,\n 'unsigned short': PRIM_USHORT,\n 'unsigned int': PRIM_UINT,\n 'unsigned long': PRIM_ULONG,\n 'unsigned long long': PRIM_ULONGLONG,\n 'float': PRIM_FLOAT,\n 'double': PRIM_DOUBLE,\n 'long double': PRIM_LONGDOUBLE,\n '_cffi_float_complex_t': PRIM_FLOATCOMPLEX,\n '_cffi_double_complex_t': PRIM_DOUBLECOMPLEX,\n '_Bool': PRIM_BOOL,\n 'wchar_t': PRIM_WCHAR,\n 'char16_t': PRIM_CHAR16,\n 'char32_t': PRIM_CHAR32,\n 'int8_t': PRIM_INT8,\n 'uint8_t': PRIM_UINT8,\n 'int16_t': PRIM_INT16,\n 'uint16_t': PRIM_UINT16,\n 'int32_t': PRIM_INT32,\n 'uint32_t': PRIM_UINT32,\n 'int64_t': PRIM_INT64,\n 'uint64_t': PRIM_UINT64,\n 'intptr_t': PRIM_INTPTR,\n 'uintptr_t': PRIM_UINTPTR,\n 'ptrdiff_t': PRIM_PTRDIFF,\n 'size_t': PRIM_SIZE,\n 'ssize_t': PRIM_SSIZE,\n 'int_least8_t': PRIM_INT_LEAST8,\n 'uint_least8_t': PRIM_UINT_LEAST8,\n 'int_least16_t': PRIM_INT_LEAST16,\n 'uint_least16_t': PRIM_UINT_LEAST16,\n 'int_least32_t': PRIM_INT_LEAST32,\n 'uint_least32_t': PRIM_UINT_LEAST32,\n 'int_least64_t': PRIM_INT_LEAST64,\n 'uint_least64_t': PRIM_UINT_LEAST64,\n 'int_fast8_t': PRIM_INT_FAST8,\n 'uint_fast8_t': PRIM_UINT_FAST8,\n 'int_fast16_t': PRIM_INT_FAST16,\n 'uint_fast16_t': PRIM_UINT_FAST16,\n 'int_fast32_t': PRIM_INT_FAST32,\n 'uint_fast32_t': PRIM_UINT_FAST32,\n 'int_fast64_t': PRIM_INT_FAST64,\n 'uint_fast64_t': PRIM_UINT_FAST64,\n 'intmax_t': PRIM_INTMAX,\n 'uintmax_t': PRIM_UINTMAX,\n }\n\nF_UNION = 0x01\nF_CHECK_FIELDS = 0x02\nF_PACKED = 0x04\nF_EXTERNAL = 0x08\nF_OPAQUE = 0x10\n\nG_FLAGS = dict([('_CFFI_' + _key, globals()[_key])\n for _key in ['F_UNION', 'F_CHECK_FIELDS', 'F_PACKED',\n 'F_EXTERNAL', 'F_OPAQUE']])\n\nCLASS_NAME = {}\nfor _name, _value in list(globals().items()):\n if _name.startswith('OP_') and isinstance(_value, int):\n CLASS_NAME[_value] = _name[3:]\n
|
.venv\Lib\site-packages\cffi\cffi_opcode.py
|
cffi_opcode.py
|
Python
| 5,731 | 0.95 | 0.069519 | 0 |
react-lib
| 13 |
2024-05-09T20:38:36.203255
|
BSD-3-Clause
| false |
03105b61433c21a14054e155c387af1d
|
\nclass FFIError(Exception):\n __module__ = 'cffi'\n\nclass CDefError(Exception):\n __module__ = 'cffi'\n def __str__(self):\n try:\n current_decl = self.args[1]\n filename = current_decl.coord.file\n linenum = current_decl.coord.line\n prefix = '%s:%d: ' % (filename, linenum)\n except (AttributeError, TypeError, IndexError):\n prefix = ''\n return '%s%s' % (prefix, self.args[0])\n\nclass VerificationError(Exception):\n """ An error raised when verification fails\n """\n __module__ = 'cffi'\n\nclass VerificationMissing(Exception):\n """ An error raised when incomplete structures are passed into\n cdef, but no verification has been done\n """\n __module__ = 'cffi'\n\nclass PkgConfigError(Exception):\n """ An error raised for missing modules in pkg-config\n """\n __module__ = 'cffi'\n
|
.venv\Lib\site-packages\cffi\error.py
|
error.py
|
Python
| 877 | 0.85 | 0.258065 | 0 |
vue-tools
| 342 |
2024-08-07T06:43:50.956842
|
GPL-3.0
| false |
7f02d866313a0d928aa9c1162eafb9e7
|
import sys, os\nfrom .error import VerificationError\n\n\nLIST_OF_FILE_NAMES = ['sources', 'include_dirs', 'library_dirs',\n 'extra_objects', 'depends']\n\ndef get_extension(srcfilename, modname, sources=(), **kwds):\n from cffi._shimmed_dist_utils import Extension\n allsources = [srcfilename]\n for src in sources:\n allsources.append(os.path.normpath(src))\n return Extension(name=modname, sources=allsources, **kwds)\n\ndef compile(tmpdir, ext, compiler_verbose=0, debug=None):\n """Compile a C extension module using distutils."""\n\n saved_environ = os.environ.copy()\n try:\n outputfilename = _build(tmpdir, ext, compiler_verbose, debug)\n outputfilename = os.path.abspath(outputfilename)\n finally:\n # workaround for a distutils bugs where some env vars can\n # become longer and longer every time it is used\n for key, value in saved_environ.items():\n if os.environ.get(key) != value:\n os.environ[key] = value\n return outputfilename\n\ndef _build(tmpdir, ext, compiler_verbose=0, debug=None):\n # XXX compact but horrible :-(\n from cffi._shimmed_dist_utils import Distribution, CompileError, LinkError, set_threshold, set_verbosity\n\n dist = Distribution({'ext_modules': [ext]})\n dist.parse_config_files()\n options = dist.get_option_dict('build_ext')\n if debug is None:\n debug = sys.flags.debug\n options['debug'] = ('ffiplatform', debug)\n options['force'] = ('ffiplatform', True)\n options['build_lib'] = ('ffiplatform', tmpdir)\n options['build_temp'] = ('ffiplatform', tmpdir)\n #\n try:\n old_level = set_threshold(0) or 0\n try:\n set_verbosity(compiler_verbose)\n dist.run_command('build_ext')\n cmd_obj = dist.get_command_obj('build_ext')\n [soname] = cmd_obj.get_outputs()\n finally:\n set_threshold(old_level)\n except (CompileError, LinkError) as e:\n raise VerificationError('%s: %s' % (e.__class__.__name__, e))\n #\n return soname\n\ntry:\n from os.path import samefile\nexcept ImportError:\n def samefile(f1, f2):\n return os.path.abspath(f1) == os.path.abspath(f2)\n\ndef maybe_relative_path(path):\n if not os.path.isabs(path):\n return path # already relative\n dir = path\n names = []\n while True:\n prevdir = dir\n dir, name = os.path.split(prevdir)\n if dir == prevdir or not dir:\n return path # failed to make it relative\n names.append(name)\n try:\n if samefile(dir, os.curdir):\n names.reverse()\n return os.path.join(*names)\n except OSError:\n pass\n\n# ____________________________________________________________\n\ntry:\n int_or_long = (int, long)\n import cStringIO\nexcept NameError:\n int_or_long = int # Python 3\n import io as cStringIO\n\ndef _flatten(x, f):\n if isinstance(x, str):\n f.write('%ds%s' % (len(x), x))\n elif isinstance(x, dict):\n keys = sorted(x.keys())\n f.write('%dd' % len(keys))\n for key in keys:\n _flatten(key, f)\n _flatten(x[key], f)\n elif isinstance(x, (list, tuple)):\n f.write('%dl' % len(x))\n for value in x:\n _flatten(value, f)\n elif isinstance(x, int_or_long):\n f.write('%di' % (x,))\n else:\n raise TypeError(\n "the keywords to verify() contains unsupported object %r" % (x,))\n\ndef flatten(x):\n f = cStringIO.StringIO()\n _flatten(x, f)\n return f.getvalue()\n
|
.venv\Lib\site-packages\cffi\ffiplatform.py
|
ffiplatform.py
|
Python
| 3,584 | 0.95 | 0.221239 | 0.06 |
node-utils
| 509 |
2024-05-07T07:51:24.333994
|
GPL-3.0
| false |
7c1aaf7202d5575e4daaf1dfcf5e7b35
|
import sys\n\nif sys.version_info < (3,):\n try:\n from thread import allocate_lock\n except ImportError:\n from dummy_thread import allocate_lock\nelse:\n try:\n from _thread import allocate_lock\n except ImportError:\n from _dummy_thread import allocate_lock\n\n\n##import sys\n##l1 = allocate_lock\n\n##class allocate_lock(object):\n## def __init__(self):\n## self._real = l1()\n## def __enter__(self):\n## for i in range(4, 0, -1):\n## print sys._getframe(i).f_code\n## print\n## return self._real.__enter__()\n## def __exit__(self, *args):\n## return self._real.__exit__(*args)\n## def acquire(self, f):\n## assert f is False\n## return self._real.acquire(f)\n
|
.venv\Lib\site-packages\cffi\lock.py
|
lock.py
|
Python
| 747 | 0.95 | 0.3 | 0.576923 |
react-lib
| 816 |
2023-09-21T10:23:32.228082
|
MIT
| false |
4cc065d5df79eddf6bcfc06bd4a8e54a
|
import types\nimport weakref\n\nfrom .lock import allocate_lock\nfrom .error import CDefError, VerificationError, VerificationMissing\n\n# type qualifiers\nQ_CONST = 0x01\nQ_RESTRICT = 0x02\nQ_VOLATILE = 0x04\n\ndef qualify(quals, replace_with):\n if quals & Q_CONST:\n replace_with = ' const ' + replace_with.lstrip()\n if quals & Q_VOLATILE:\n replace_with = ' volatile ' + replace_with.lstrip()\n if quals & Q_RESTRICT:\n # It seems that __restrict is supported by gcc and msvc.\n # If you hit some different compiler, add a #define in\n # _cffi_include.h for it (and in its copies, documented there)\n replace_with = ' __restrict ' + replace_with.lstrip()\n return replace_with\n\n\nclass BaseTypeByIdentity(object):\n is_array_type = False\n is_raw_function = False\n\n def get_c_name(self, replace_with='', context='a C file', quals=0):\n result = self.c_name_with_marker\n assert result.count('&') == 1\n # some logic duplication with ffi.getctype()... :-(\n replace_with = replace_with.strip()\n if replace_with:\n if replace_with.startswith('*') and '&[' in result:\n replace_with = '(%s)' % replace_with\n elif not replace_with[0] in '[(':\n replace_with = ' ' + replace_with\n replace_with = qualify(quals, replace_with)\n result = result.replace('&', replace_with)\n if '$' in result:\n raise VerificationError(\n "cannot generate '%s' in %s: unknown type name"\n % (self._get_c_name(), context))\n return result\n\n def _get_c_name(self):\n return self.c_name_with_marker.replace('&', '')\n\n def has_c_name(self):\n return '$' not in self._get_c_name()\n\n def is_integer_type(self):\n return False\n\n def get_cached_btype(self, ffi, finishlist, can_delay=False):\n try:\n BType = ffi._cached_btypes[self]\n except KeyError:\n BType = self.build_backend_type(ffi, finishlist)\n BType2 = ffi._cached_btypes.setdefault(self, BType)\n assert BType2 is BType\n return BType\n\n def __repr__(self):\n return '<%s>' % (self._get_c_name(),)\n\n def _get_items(self):\n return [(name, getattr(self, name)) for name in self._attrs_]\n\n\nclass BaseType(BaseTypeByIdentity):\n\n def __eq__(self, other):\n return (self.__class__ == other.__class__ and\n self._get_items() == other._get_items())\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n return hash((self.__class__, tuple(self._get_items())))\n\n\nclass VoidType(BaseType):\n _attrs_ = ()\n\n def __init__(self):\n self.c_name_with_marker = 'void&'\n\n def build_backend_type(self, ffi, finishlist):\n return global_cache(self, ffi, 'new_void_type')\n\nvoid_type = VoidType()\n\n\nclass BasePrimitiveType(BaseType):\n def is_complex_type(self):\n return False\n\n\nclass PrimitiveType(BasePrimitiveType):\n _attrs_ = ('name',)\n\n ALL_PRIMITIVE_TYPES = {\n 'char': 'c',\n 'short': 'i',\n 'int': 'i',\n 'long': 'i',\n 'long long': 'i',\n 'signed char': 'i',\n 'unsigned char': 'i',\n 'unsigned short': 'i',\n 'unsigned int': 'i',\n 'unsigned long': 'i',\n 'unsigned long long': 'i',\n 'float': 'f',\n 'double': 'f',\n 'long double': 'f',\n '_cffi_float_complex_t': 'j',\n '_cffi_double_complex_t': 'j',\n '_Bool': 'i',\n # the following types are not primitive in the C sense\n 'wchar_t': 'c',\n 'char16_t': 'c',\n 'char32_t': 'c',\n 'int8_t': 'i',\n 'uint8_t': 'i',\n 'int16_t': 'i',\n 'uint16_t': 'i',\n 'int32_t': 'i',\n 'uint32_t': 'i',\n 'int64_t': 'i',\n 'uint64_t': 'i',\n 'int_least8_t': 'i',\n 'uint_least8_t': 'i',\n 'int_least16_t': 'i',\n 'uint_least16_t': 'i',\n 'int_least32_t': 'i',\n 'uint_least32_t': 'i',\n 'int_least64_t': 'i',\n 'uint_least64_t': 'i',\n 'int_fast8_t': 'i',\n 'uint_fast8_t': 'i',\n 'int_fast16_t': 'i',\n 'uint_fast16_t': 'i',\n 'int_fast32_t': 'i',\n 'uint_fast32_t': 'i',\n 'int_fast64_t': 'i',\n 'uint_fast64_t': 'i',\n 'intptr_t': 'i',\n 'uintptr_t': 'i',\n 'intmax_t': 'i',\n 'uintmax_t': 'i',\n 'ptrdiff_t': 'i',\n 'size_t': 'i',\n 'ssize_t': 'i',\n }\n\n def __init__(self, name):\n assert name in self.ALL_PRIMITIVE_TYPES\n self.name = name\n self.c_name_with_marker = name + '&'\n\n def is_char_type(self):\n return self.ALL_PRIMITIVE_TYPES[self.name] == 'c'\n def is_integer_type(self):\n return self.ALL_PRIMITIVE_TYPES[self.name] == 'i'\n def is_float_type(self):\n return self.ALL_PRIMITIVE_TYPES[self.name] == 'f'\n def is_complex_type(self):\n return self.ALL_PRIMITIVE_TYPES[self.name] == 'j'\n\n def build_backend_type(self, ffi, finishlist):\n return global_cache(self, ffi, 'new_primitive_type', self.name)\n\n\nclass UnknownIntegerType(BasePrimitiveType):\n _attrs_ = ('name',)\n\n def __init__(self, name):\n self.name = name\n self.c_name_with_marker = name + '&'\n\n def is_integer_type(self):\n return True\n\n def build_backend_type(self, ffi, finishlist):\n raise NotImplementedError("integer type '%s' can only be used after "\n "compilation" % self.name)\n\nclass UnknownFloatType(BasePrimitiveType):\n _attrs_ = ('name', )\n\n def __init__(self, name):\n self.name = name\n self.c_name_with_marker = name + '&'\n\n def build_backend_type(self, ffi, finishlist):\n raise NotImplementedError("float type '%s' can only be used after "\n "compilation" % self.name)\n\n\nclass BaseFunctionType(BaseType):\n _attrs_ = ('args', 'result', 'ellipsis', 'abi')\n\n def __init__(self, args, result, ellipsis, abi=None):\n self.args = args\n self.result = result\n self.ellipsis = ellipsis\n self.abi = abi\n #\n reprargs = [arg._get_c_name() for arg in self.args]\n if self.ellipsis:\n reprargs.append('...')\n reprargs = reprargs or ['void']\n replace_with = self._base_pattern % (', '.join(reprargs),)\n if abi is not None:\n replace_with = replace_with[:1] + abi + ' ' + replace_with[1:]\n self.c_name_with_marker = (\n self.result.c_name_with_marker.replace('&', replace_with))\n\n\nclass RawFunctionType(BaseFunctionType):\n # Corresponds to a C type like 'int(int)', which is the C type of\n # a function, but not a pointer-to-function. The backend has no\n # notion of such a type; it's used temporarily by parsing.\n _base_pattern = '(&)(%s)'\n is_raw_function = True\n\n def build_backend_type(self, ffi, finishlist):\n raise CDefError("cannot render the type %r: it is a function "\n "type, not a pointer-to-function type" % (self,))\n\n def as_function_pointer(self):\n return FunctionPtrType(self.args, self.result, self.ellipsis, self.abi)\n\n\nclass FunctionPtrType(BaseFunctionType):\n _base_pattern = '(*&)(%s)'\n\n def build_backend_type(self, ffi, finishlist):\n result = self.result.get_cached_btype(ffi, finishlist)\n args = []\n for tp in self.args:\n args.append(tp.get_cached_btype(ffi, finishlist))\n abi_args = ()\n if self.abi == "__stdcall":\n if not self.ellipsis: # __stdcall ignored for variadic funcs\n try:\n abi_args = (ffi._backend.FFI_STDCALL,)\n except AttributeError:\n pass\n return global_cache(self, ffi, 'new_function_type',\n tuple(args), result, self.ellipsis, *abi_args)\n\n def as_raw_function(self):\n return RawFunctionType(self.args, self.result, self.ellipsis, self.abi)\n\n\nclass PointerType(BaseType):\n _attrs_ = ('totype', 'quals')\n\n def __init__(self, totype, quals=0):\n self.totype = totype\n self.quals = quals\n extra = " *&"\n if totype.is_array_type:\n extra = "(%s)" % (extra.lstrip(),)\n extra = qualify(quals, extra)\n self.c_name_with_marker = totype.c_name_with_marker.replace('&', extra)\n\n def build_backend_type(self, ffi, finishlist):\n BItem = self.totype.get_cached_btype(ffi, finishlist, can_delay=True)\n return global_cache(self, ffi, 'new_pointer_type', BItem)\n\nvoidp_type = PointerType(void_type)\n\ndef ConstPointerType(totype):\n return PointerType(totype, Q_CONST)\n\nconst_voidp_type = ConstPointerType(void_type)\n\n\nclass NamedPointerType(PointerType):\n _attrs_ = ('totype', 'name')\n\n def __init__(self, totype, name, quals=0):\n PointerType.__init__(self, totype, quals)\n self.name = name\n self.c_name_with_marker = name + '&'\n\n\nclass ArrayType(BaseType):\n _attrs_ = ('item', 'length')\n is_array_type = True\n\n def __init__(self, item, length):\n self.item = item\n self.length = length\n #\n if length is None:\n brackets = '&[]'\n elif length == '...':\n brackets = '&[/*...*/]'\n else:\n brackets = '&[%s]' % length\n self.c_name_with_marker = (\n self.item.c_name_with_marker.replace('&', brackets))\n\n def length_is_unknown(self):\n return isinstance(self.length, str)\n\n def resolve_length(self, newlength):\n return ArrayType(self.item, newlength)\n\n def build_backend_type(self, ffi, finishlist):\n if self.length_is_unknown():\n raise CDefError("cannot render the type %r: unknown length" %\n (self,))\n self.item.get_cached_btype(ffi, finishlist) # force the item BType\n BPtrItem = PointerType(self.item).get_cached_btype(ffi, finishlist)\n return global_cache(self, ffi, 'new_array_type', BPtrItem, self.length)\n\nchar_array_type = ArrayType(PrimitiveType('char'), None)\n\n\nclass StructOrUnionOrEnum(BaseTypeByIdentity):\n _attrs_ = ('name',)\n forcename = None\n\n def build_c_name_with_marker(self):\n name = self.forcename or '%s %s' % (self.kind, self.name)\n self.c_name_with_marker = name + '&'\n\n def force_the_name(self, forcename):\n self.forcename = forcename\n self.build_c_name_with_marker()\n\n def get_official_name(self):\n assert self.c_name_with_marker.endswith('&')\n return self.c_name_with_marker[:-1]\n\n\nclass StructOrUnion(StructOrUnionOrEnum):\n fixedlayout = None\n completed = 0\n partial = False\n packed = 0\n\n def __init__(self, name, fldnames, fldtypes, fldbitsize, fldquals=None):\n self.name = name\n self.fldnames = fldnames\n self.fldtypes = fldtypes\n self.fldbitsize = fldbitsize\n self.fldquals = fldquals\n self.build_c_name_with_marker()\n\n def anonymous_struct_fields(self):\n if self.fldtypes is not None:\n for name, type in zip(self.fldnames, self.fldtypes):\n if name == '' and isinstance(type, StructOrUnion):\n yield type\n\n def enumfields(self, expand_anonymous_struct_union=True):\n fldquals = self.fldquals\n if fldquals is None:\n fldquals = (0,) * len(self.fldnames)\n for name, type, bitsize, quals in zip(self.fldnames, self.fldtypes,\n self.fldbitsize, fldquals):\n if (name == '' and isinstance(type, StructOrUnion)\n and expand_anonymous_struct_union):\n # nested anonymous struct/union\n for result in type.enumfields():\n yield result\n else:\n yield (name, type, bitsize, quals)\n\n def force_flatten(self):\n # force the struct or union to have a declaration that lists\n # directly all fields returned by enumfields(), flattening\n # nested anonymous structs/unions.\n names = []\n types = []\n bitsizes = []\n fldquals = []\n for name, type, bitsize, quals in self.enumfields():\n names.append(name)\n types.append(type)\n bitsizes.append(bitsize)\n fldquals.append(quals)\n self.fldnames = tuple(names)\n self.fldtypes = tuple(types)\n self.fldbitsize = tuple(bitsizes)\n self.fldquals = tuple(fldquals)\n\n def get_cached_btype(self, ffi, finishlist, can_delay=False):\n BType = StructOrUnionOrEnum.get_cached_btype(self, ffi, finishlist,\n can_delay)\n if not can_delay:\n self.finish_backend_type(ffi, finishlist)\n return BType\n\n def finish_backend_type(self, ffi, finishlist):\n if self.completed:\n if self.completed != 2:\n raise NotImplementedError("recursive structure declaration "\n "for '%s'" % (self.name,))\n return\n BType = ffi._cached_btypes[self]\n #\n self.completed = 1\n #\n if self.fldtypes is None:\n pass # not completing it: it's an opaque struct\n #\n elif self.fixedlayout is None:\n fldtypes = [tp.get_cached_btype(ffi, finishlist)\n for tp in self.fldtypes]\n lst = list(zip(self.fldnames, fldtypes, self.fldbitsize))\n extra_flags = ()\n if self.packed:\n if self.packed == 1:\n extra_flags = (8,) # SF_PACKED\n else:\n extra_flags = (0, self.packed)\n ffi._backend.complete_struct_or_union(BType, lst, self,\n -1, -1, *extra_flags)\n #\n else:\n fldtypes = []\n fieldofs, fieldsize, totalsize, totalalignment = self.fixedlayout\n for i in range(len(self.fldnames)):\n fsize = fieldsize[i]\n ftype = self.fldtypes[i]\n #\n if isinstance(ftype, ArrayType) and ftype.length_is_unknown():\n # fix the length to match the total size\n BItemType = ftype.item.get_cached_btype(ffi, finishlist)\n nlen, nrest = divmod(fsize, ffi.sizeof(BItemType))\n if nrest != 0:\n self._verification_error(\n "field '%s.%s' has a bogus size?" % (\n self.name, self.fldnames[i] or '{}'))\n ftype = ftype.resolve_length(nlen)\n self.fldtypes = (self.fldtypes[:i] + (ftype,) +\n self.fldtypes[i+1:])\n #\n BFieldType = ftype.get_cached_btype(ffi, finishlist)\n if isinstance(ftype, ArrayType) and ftype.length is None:\n assert fsize == 0\n else:\n bitemsize = ffi.sizeof(BFieldType)\n if bitemsize != fsize:\n self._verification_error(\n "field '%s.%s' is declared as %d bytes, but is "\n "really %d bytes" % (self.name,\n self.fldnames[i] or '{}',\n bitemsize, fsize))\n fldtypes.append(BFieldType)\n #\n lst = list(zip(self.fldnames, fldtypes, self.fldbitsize, fieldofs))\n ffi._backend.complete_struct_or_union(BType, lst, self,\n totalsize, totalalignment)\n self.completed = 2\n\n def _verification_error(self, msg):\n raise VerificationError(msg)\n\n def check_not_partial(self):\n if self.partial and self.fixedlayout is None:\n raise VerificationMissing(self._get_c_name())\n\n def build_backend_type(self, ffi, finishlist):\n self.check_not_partial()\n finishlist.append(self)\n #\n return global_cache(self, ffi, 'new_%s_type' % self.kind,\n self.get_official_name(), key=self)\n\n\nclass StructType(StructOrUnion):\n kind = 'struct'\n\n\nclass UnionType(StructOrUnion):\n kind = 'union'\n\n\nclass EnumType(StructOrUnionOrEnum):\n kind = 'enum'\n partial = False\n partial_resolved = False\n\n def __init__(self, name, enumerators, enumvalues, baseinttype=None):\n self.name = name\n self.enumerators = enumerators\n self.enumvalues = enumvalues\n self.baseinttype = baseinttype\n self.build_c_name_with_marker()\n\n def force_the_name(self, forcename):\n StructOrUnionOrEnum.force_the_name(self, forcename)\n if self.forcename is None:\n name = self.get_official_name()\n self.forcename = '$' + name.replace(' ', '_')\n\n def check_not_partial(self):\n if self.partial and not self.partial_resolved:\n raise VerificationMissing(self._get_c_name())\n\n def build_backend_type(self, ffi, finishlist):\n self.check_not_partial()\n base_btype = self.build_baseinttype(ffi, finishlist)\n return global_cache(self, ffi, 'new_enum_type',\n self.get_official_name(),\n self.enumerators, self.enumvalues,\n base_btype, key=self)\n\n def build_baseinttype(self, ffi, finishlist):\n if self.baseinttype is not None:\n return self.baseinttype.get_cached_btype(ffi, finishlist)\n #\n if self.enumvalues:\n smallest_value = min(self.enumvalues)\n largest_value = max(self.enumvalues)\n else:\n import warnings\n try:\n # XXX! The goal is to ensure that the warnings.warn()\n # will not suppress the warning. We want to get it\n # several times if we reach this point several times.\n __warningregistry__.clear()\n except NameError:\n pass\n warnings.warn("%r has no values explicitly defined; "\n "guessing that it is equivalent to 'unsigned int'"\n % self._get_c_name())\n smallest_value = largest_value = 0\n if smallest_value < 0: # needs a signed type\n sign = 1\n candidate1 = PrimitiveType("int")\n candidate2 = PrimitiveType("long")\n else:\n sign = 0\n candidate1 = PrimitiveType("unsigned int")\n candidate2 = PrimitiveType("unsigned long")\n btype1 = candidate1.get_cached_btype(ffi, finishlist)\n btype2 = candidate2.get_cached_btype(ffi, finishlist)\n size1 = ffi.sizeof(btype1)\n size2 = ffi.sizeof(btype2)\n if (smallest_value >= ((-1) << (8*size1-1)) and\n largest_value < (1 << (8*size1-sign))):\n return btype1\n if (smallest_value >= ((-1) << (8*size2-1)) and\n largest_value < (1 << (8*size2-sign))):\n return btype2\n raise CDefError("%s values don't all fit into either 'long' "\n "or 'unsigned long'" % self._get_c_name())\n\ndef unknown_type(name, structname=None):\n if structname is None:\n structname = '$%s' % name\n tp = StructType(structname, None, None, None)\n tp.force_the_name(name)\n tp.origin = "unknown_type"\n return tp\n\ndef unknown_ptr_type(name, structname=None):\n if structname is None:\n structname = '$$%s' % name\n tp = StructType(structname, None, None, None)\n return NamedPointerType(tp, name)\n\n\nglobal_lock = allocate_lock()\n_typecache_cffi_backend = weakref.WeakValueDictionary()\n\ndef get_typecache(backend):\n # returns _typecache_cffi_backend if backend is the _cffi_backend\n # module, or type(backend).__typecache if backend is an instance of\n # CTypesBackend (or some FakeBackend class during tests)\n if isinstance(backend, types.ModuleType):\n return _typecache_cffi_backend\n with global_lock:\n if not hasattr(type(backend), '__typecache'):\n type(backend).__typecache = weakref.WeakValueDictionary()\n return type(backend).__typecache\n\ndef global_cache(srctype, ffi, funcname, *args, **kwds):\n key = kwds.pop('key', (funcname, args))\n assert not kwds\n try:\n return ffi._typecache[key]\n except KeyError:\n pass\n try:\n res = getattr(ffi._backend, funcname)(*args)\n except NotImplementedError as e:\n raise NotImplementedError("%s: %r: %s" % (funcname, srctype, e))\n # note that setdefault() on WeakValueDictionary is not atomic\n # and contains a rare bug (http://bugs.python.org/issue19542);\n # we have to use a lock and do it ourselves\n cache = ffi._typecache\n with global_lock:\n res1 = cache.get(key)\n if res1 is None:\n cache[key] = res\n return res\n else:\n return res1\n\ndef pointer_cache(ffi, BType):\n return global_cache('?', ffi, 'new_pointer_type', BType)\n\ndef attach_exception_info(e, name):\n if e.args and type(e.args[0]) is str:\n e.args = ('%s: %s' % (name, e.args[0]),) + e.args[1:]\n
|
.venv\Lib\site-packages\cffi\model.py
|
model.py
|
Python
| 21,797 | 0.95 | 0.234628 | 0.065764 |
vue-tools
| 410 |
2025-03-21T02:54:47.908481
|
BSD-3-Clause
| false |
309212a09385f6c54065bf261dc42cea
|
\n/* This part is from file 'cffi/parse_c_type.h'. It is copied at the\n beginning of C sources generated by CFFI's ffi.set_source(). */\n\ntypedef void *_cffi_opcode_t;\n\n#define _CFFI_OP(opcode, arg) (_cffi_opcode_t)(opcode | (((uintptr_t)(arg)) << 8))\n#define _CFFI_GETOP(cffi_opcode) ((unsigned char)(uintptr_t)cffi_opcode)\n#define _CFFI_GETARG(cffi_opcode) (((intptr_t)cffi_opcode) >> 8)\n\n#define _CFFI_OP_PRIMITIVE 1\n#define _CFFI_OP_POINTER 3\n#define _CFFI_OP_ARRAY 5\n#define _CFFI_OP_OPEN_ARRAY 7\n#define _CFFI_OP_STRUCT_UNION 9\n#define _CFFI_OP_ENUM 11\n#define _CFFI_OP_FUNCTION 13\n#define _CFFI_OP_FUNCTION_END 15\n#define _CFFI_OP_NOOP 17\n#define _CFFI_OP_BITFIELD 19\n#define _CFFI_OP_TYPENAME 21\n#define _CFFI_OP_CPYTHON_BLTN_V 23 // varargs\n#define _CFFI_OP_CPYTHON_BLTN_N 25 // noargs\n#define _CFFI_OP_CPYTHON_BLTN_O 27 // O (i.e. a single arg)\n#define _CFFI_OP_CONSTANT 29\n#define _CFFI_OP_CONSTANT_INT 31\n#define _CFFI_OP_GLOBAL_VAR 33\n#define _CFFI_OP_DLOPEN_FUNC 35\n#define _CFFI_OP_DLOPEN_CONST 37\n#define _CFFI_OP_GLOBAL_VAR_F 39\n#define _CFFI_OP_EXTERN_PYTHON 41\n\n#define _CFFI_PRIM_VOID 0\n#define _CFFI_PRIM_BOOL 1\n#define _CFFI_PRIM_CHAR 2\n#define _CFFI_PRIM_SCHAR 3\n#define _CFFI_PRIM_UCHAR 4\n#define _CFFI_PRIM_SHORT 5\n#define _CFFI_PRIM_USHORT 6\n#define _CFFI_PRIM_INT 7\n#define _CFFI_PRIM_UINT 8\n#define _CFFI_PRIM_LONG 9\n#define _CFFI_PRIM_ULONG 10\n#define _CFFI_PRIM_LONGLONG 11\n#define _CFFI_PRIM_ULONGLONG 12\n#define _CFFI_PRIM_FLOAT 13\n#define _CFFI_PRIM_DOUBLE 14\n#define _CFFI_PRIM_LONGDOUBLE 15\n\n#define _CFFI_PRIM_WCHAR 16\n#define _CFFI_PRIM_INT8 17\n#define _CFFI_PRIM_UINT8 18\n#define _CFFI_PRIM_INT16 19\n#define _CFFI_PRIM_UINT16 20\n#define _CFFI_PRIM_INT32 21\n#define _CFFI_PRIM_UINT32 22\n#define _CFFI_PRIM_INT64 23\n#define _CFFI_PRIM_UINT64 24\n#define _CFFI_PRIM_INTPTR 25\n#define _CFFI_PRIM_UINTPTR 26\n#define _CFFI_PRIM_PTRDIFF 27\n#define _CFFI_PRIM_SIZE 28\n#define _CFFI_PRIM_SSIZE 29\n#define _CFFI_PRIM_INT_LEAST8 30\n#define _CFFI_PRIM_UINT_LEAST8 31\n#define _CFFI_PRIM_INT_LEAST16 32\n#define _CFFI_PRIM_UINT_LEAST16 33\n#define _CFFI_PRIM_INT_LEAST32 34\n#define _CFFI_PRIM_UINT_LEAST32 35\n#define _CFFI_PRIM_INT_LEAST64 36\n#define _CFFI_PRIM_UINT_LEAST64 37\n#define _CFFI_PRIM_INT_FAST8 38\n#define _CFFI_PRIM_UINT_FAST8 39\n#define _CFFI_PRIM_INT_FAST16 40\n#define _CFFI_PRIM_UINT_FAST16 41\n#define _CFFI_PRIM_INT_FAST32 42\n#define _CFFI_PRIM_UINT_FAST32 43\n#define _CFFI_PRIM_INT_FAST64 44\n#define _CFFI_PRIM_UINT_FAST64 45\n#define _CFFI_PRIM_INTMAX 46\n#define _CFFI_PRIM_UINTMAX 47\n#define _CFFI_PRIM_FLOATCOMPLEX 48\n#define _CFFI_PRIM_DOUBLECOMPLEX 49\n#define _CFFI_PRIM_CHAR16 50\n#define _CFFI_PRIM_CHAR32 51\n\n#define _CFFI__NUM_PRIM 52\n#define _CFFI__UNKNOWN_PRIM (-1)\n#define _CFFI__UNKNOWN_FLOAT_PRIM (-2)\n#define _CFFI__UNKNOWN_LONG_DOUBLE (-3)\n\n#define _CFFI__IO_FILE_STRUCT (-1)\n\n\nstruct _cffi_global_s {\n const char *name;\n void *address;\n _cffi_opcode_t type_op;\n void *size_or_direct_fn; // OP_GLOBAL_VAR: size, or 0 if unknown\n // OP_CPYTHON_BLTN_*: addr of direct function\n};\n\nstruct _cffi_getconst_s {\n unsigned long long value;\n const struct _cffi_type_context_s *ctx;\n int gindex;\n};\n\nstruct _cffi_struct_union_s {\n const char *name;\n int type_index; // -> _cffi_types, on a OP_STRUCT_UNION\n int flags; // _CFFI_F_* flags below\n size_t size;\n int alignment;\n int first_field_index; // -> _cffi_fields array\n int num_fields;\n};\n#define _CFFI_F_UNION 0x01 // is a union, not a struct\n#define _CFFI_F_CHECK_FIELDS 0x02 // complain if fields are not in the\n // "standard layout" or if some are missing\n#define _CFFI_F_PACKED 0x04 // for CHECK_FIELDS, assume a packed struct\n#define _CFFI_F_EXTERNAL 0x08 // in some other ffi.include()\n#define _CFFI_F_OPAQUE 0x10 // opaque\n\nstruct _cffi_field_s {\n const char *name;\n size_t field_offset;\n size_t field_size;\n _cffi_opcode_t field_type_op;\n};\n\nstruct _cffi_enum_s {\n const char *name;\n int type_index; // -> _cffi_types, on a OP_ENUM\n int type_prim; // _CFFI_PRIM_xxx\n const char *enumerators; // comma-delimited string\n};\n\nstruct _cffi_typename_s {\n const char *name;\n int type_index; /* if opaque, points to a possibly artificial\n OP_STRUCT which is itself opaque */\n};\n\nstruct _cffi_type_context_s {\n _cffi_opcode_t *types;\n const struct _cffi_global_s *globals;\n const struct _cffi_field_s *fields;\n const struct _cffi_struct_union_s *struct_unions;\n const struct _cffi_enum_s *enums;\n const struct _cffi_typename_s *typenames;\n int num_globals;\n int num_struct_unions;\n int num_enums;\n int num_typenames;\n const char *const *includes;\n int num_types;\n int flags; /* future extension */\n};\n\nstruct _cffi_parse_info_s {\n const struct _cffi_type_context_s *ctx;\n _cffi_opcode_t *output;\n unsigned int output_size;\n size_t error_location;\n const char *error_message;\n};\n\nstruct _cffi_externpy_s {\n const char *name;\n size_t size_of_result;\n void *reserved1, *reserved2;\n};\n\n#ifdef _CFFI_INTERNAL\nstatic int parse_c_type(struct _cffi_parse_info_s *info, const char *input);\nstatic int search_in_globals(const struct _cffi_type_context_s *ctx,\n const char *search, size_t search_len);\nstatic int search_in_struct_unions(const struct _cffi_type_context_s *ctx,\n const char *search, size_t search_len);\n#endif\n
|
.venv\Lib\site-packages\cffi\parse_c_type.h
|
parse_c_type.h
|
C
| 5,976 | 0.95 | 0.033149 | 0.561728 |
node-utils
| 571 |
2023-09-18T14:55:17.021508
|
Apache-2.0
| false |
0138c9742e437b5c5f5468acff804f27
|
#\n# DEPRECATED: implementation for ffi.verify()\n#\nimport sys\nfrom . import model\nfrom .error import VerificationError\nfrom . import _imp_emulation as imp\n\n\nclass VCPythonEngine(object):\n _class_key = 'x'\n _gen_python_module = True\n\n def __init__(self, verifier):\n self.verifier = verifier\n self.ffi = verifier.ffi\n self._struct_pending_verification = {}\n self._types_of_builtin_functions = {}\n\n def patch_extension_kwds(self, kwds):\n pass\n\n def find_module(self, module_name, path, so_suffixes):\n try:\n f, filename, descr = imp.find_module(module_name, path)\n except ImportError:\n return None\n if f is not None:\n f.close()\n # Note that after a setuptools installation, there are both .py\n # and .so files with the same basename. The code here relies on\n # imp.find_module() locating the .so in priority.\n if descr[0] not in so_suffixes:\n return None\n return filename\n\n def collect_types(self):\n self._typesdict = {}\n self._generate("collecttype")\n\n def _prnt(self, what=''):\n self._f.write(what + '\n')\n\n def _gettypenum(self, type):\n # a KeyError here is a bug. please report it! :-)\n return self._typesdict[type]\n\n def _do_collect_type(self, tp):\n if ((not isinstance(tp, model.PrimitiveType)\n or tp.name == 'long double')\n and tp not in self._typesdict):\n num = len(self._typesdict)\n self._typesdict[tp] = num\n\n def write_source_to_f(self):\n self.collect_types()\n #\n # The new module will have a _cffi_setup() function that receives\n # objects from the ffi world, and that calls some setup code in\n # the module. This setup code is split in several independent\n # functions, e.g. one per constant. The functions are "chained"\n # by ending in a tail call to each other.\n #\n # This is further split in two chained lists, depending on if we\n # can do it at import-time or if we must wait for _cffi_setup() to\n # provide us with the <ctype> objects. This is needed because we\n # need the values of the enum constants in order to build the\n # <ctype 'enum'> that we may have to pass to _cffi_setup().\n #\n # The following two 'chained_list_constants' items contains\n # the head of these two chained lists, as a string that gives the\n # call to do, if any.\n self._chained_list_constants = ['((void)lib,0)', '((void)lib,0)']\n #\n prnt = self._prnt\n # first paste some standard set of lines that are mostly '#define'\n prnt(cffimod_header)\n prnt()\n # then paste the C source given by the user, verbatim.\n prnt(self.verifier.preamble)\n prnt()\n #\n # call generate_cpy_xxx_decl(), for every xxx found from\n # ffi._parser._declarations. This generates all the functions.\n self._generate("decl")\n #\n # implement the function _cffi_setup_custom() as calling the\n # head of the chained list.\n self._generate_setup_custom()\n prnt()\n #\n # produce the method table, including the entries for the\n # generated Python->C function wrappers, which are done\n # by generate_cpy_function_method().\n prnt('static PyMethodDef _cffi_methods[] = {')\n self._generate("method")\n prnt(' {"_cffi_setup", _cffi_setup, METH_VARARGS, NULL},')\n prnt(' {NULL, NULL, 0, NULL} /* Sentinel */')\n prnt('};')\n prnt()\n #\n # standard init.\n modname = self.verifier.get_module_name()\n constants = self._chained_list_constants[False]\n prnt('#if PY_MAJOR_VERSION >= 3')\n prnt()\n prnt('static struct PyModuleDef _cffi_module_def = {')\n prnt(' PyModuleDef_HEAD_INIT,')\n prnt(' "%s",' % modname)\n prnt(' NULL,')\n prnt(' -1,')\n prnt(' _cffi_methods,')\n prnt(' NULL, NULL, NULL, NULL')\n prnt('};')\n prnt()\n prnt('PyMODINIT_FUNC')\n prnt('PyInit_%s(void)' % modname)\n prnt('{')\n prnt(' PyObject *lib;')\n prnt(' lib = PyModule_Create(&_cffi_module_def);')\n prnt(' if (lib == NULL)')\n prnt(' return NULL;')\n prnt(' if (%s < 0 || _cffi_init() < 0) {' % (constants,))\n prnt(' Py_DECREF(lib);')\n prnt(' return NULL;')\n prnt(' }')\n prnt(' return lib;')\n prnt('}')\n prnt()\n prnt('#else')\n prnt()\n prnt('PyMODINIT_FUNC')\n prnt('init%s(void)' % modname)\n prnt('{')\n prnt(' PyObject *lib;')\n prnt(' lib = Py_InitModule("%s", _cffi_methods);' % modname)\n prnt(' if (lib == NULL)')\n prnt(' return;')\n prnt(' if (%s < 0 || _cffi_init() < 0)' % (constants,))\n prnt(' return;')\n prnt(' return;')\n prnt('}')\n prnt()\n prnt('#endif')\n\n def load_library(self, flags=None):\n # XXX review all usages of 'self' here!\n # import it as a new extension module\n imp.acquire_lock()\n try:\n if hasattr(sys, "getdlopenflags"):\n previous_flags = sys.getdlopenflags()\n try:\n if hasattr(sys, "setdlopenflags") and flags is not None:\n sys.setdlopenflags(flags)\n module = imp.load_dynamic(self.verifier.get_module_name(),\n self.verifier.modulefilename)\n except ImportError as e:\n error = "importing %r: %s" % (self.verifier.modulefilename, e)\n raise VerificationError(error)\n finally:\n if hasattr(sys, "setdlopenflags"):\n sys.setdlopenflags(previous_flags)\n finally:\n imp.release_lock()\n #\n # call loading_cpy_struct() to get the struct layout inferred by\n # the C compiler\n self._load(module, 'loading')\n #\n # the C code will need the <ctype> objects. Collect them in\n # order in a list.\n revmapping = dict([(value, key)\n for (key, value) in self._typesdict.items()])\n lst = [revmapping[i] for i in range(len(revmapping))]\n lst = list(map(self.ffi._get_cached_btype, lst))\n #\n # build the FFILibrary class and instance and call _cffi_setup().\n # this will set up some fields like '_cffi_types', and only then\n # it will invoke the chained list of functions that will really\n # build (notably) the constant objects, as <cdata> if they are\n # pointers, and store them as attributes on the 'library' object.\n class FFILibrary(object):\n _cffi_python_module = module\n _cffi_ffi = self.ffi\n _cffi_dir = []\n def __dir__(self):\n return FFILibrary._cffi_dir + list(self.__dict__)\n library = FFILibrary()\n if module._cffi_setup(lst, VerificationError, library):\n import warnings\n warnings.warn("reimporting %r might overwrite older definitions"\n % (self.verifier.get_module_name()))\n #\n # finally, call the loaded_cpy_xxx() functions. This will perform\n # the final adjustments, like copying the Python->C wrapper\n # functions from the module to the 'library' object, and setting\n # up the FFILibrary class with properties for the global C variables.\n self._load(module, 'loaded', library=library)\n module._cffi_original_ffi = self.ffi\n module._cffi_types_of_builtin_funcs = self._types_of_builtin_functions\n return library\n\n def _get_declarations(self):\n lst = [(key, tp) for (key, (tp, qual)) in\n self.ffi._parser._declarations.items()]\n lst.sort()\n return lst\n\n def _generate(self, step_name):\n for name, tp in self._get_declarations():\n kind, realname = name.split(' ', 1)\n try:\n method = getattr(self, '_generate_cpy_%s_%s' % (kind,\n step_name))\n except AttributeError:\n raise VerificationError(\n "not implemented in verify(): %r" % name)\n try:\n method(tp, realname)\n except Exception as e:\n model.attach_exception_info(e, name)\n raise\n\n def _load(self, module, step_name, **kwds):\n for name, tp in self._get_declarations():\n kind, realname = name.split(' ', 1)\n method = getattr(self, '_%s_cpy_%s' % (step_name, kind))\n try:\n method(tp, realname, module, **kwds)\n except Exception as e:\n model.attach_exception_info(e, name)\n raise\n\n def _generate_nothing(self, tp, name):\n pass\n\n def _loaded_noop(self, tp, name, module, **kwds):\n pass\n\n # ----------\n\n def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode):\n extraarg = ''\n if isinstance(tp, model.PrimitiveType):\n if tp.is_integer_type() and tp.name != '_Bool':\n converter = '_cffi_to_c_int'\n extraarg = ', %s' % tp.name\n elif tp.is_complex_type():\n raise VerificationError(\n "not implemented in verify(): complex types")\n else:\n converter = '(%s)_cffi_to_c_%s' % (tp.get_c_name(''),\n tp.name.replace(' ', '_'))\n errvalue = '-1'\n #\n elif isinstance(tp, model.PointerType):\n self._convert_funcarg_to_c_ptr_or_array(tp, fromvar,\n tovar, errcode)\n return\n #\n elif isinstance(tp, (model.StructOrUnion, model.EnumType)):\n # a struct (not a struct pointer) as a function argument\n self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)'\n % (tovar, self._gettypenum(tp), fromvar))\n self._prnt(' %s;' % errcode)\n return\n #\n elif isinstance(tp, model.FunctionPtrType):\n converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('')\n extraarg = ', _cffi_type(%d)' % self._gettypenum(tp)\n errvalue = 'NULL'\n #\n else:\n raise NotImplementedError(tp)\n #\n self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg))\n self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % (\n tovar, tp.get_c_name(''), errvalue))\n self._prnt(' %s;' % errcode)\n\n def _extra_local_variables(self, tp, localvars, freelines):\n if isinstance(tp, model.PointerType):\n localvars.add('Py_ssize_t datasize')\n localvars.add('struct _cffi_freeme_s *large_args_free = NULL')\n freelines.add('if (large_args_free != NULL)'\n ' _cffi_free_array_arguments(large_args_free);')\n\n def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode):\n self._prnt(' datasize = _cffi_prepare_pointer_call_argument(')\n self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % (\n self._gettypenum(tp), fromvar, tovar))\n self._prnt(' if (datasize != 0) {')\n self._prnt(' %s = ((size_t)datasize) <= 640 ? '\n 'alloca((size_t)datasize) : NULL;' % (tovar,))\n self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, '\n '(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar))\n self._prnt(' datasize, &large_args_free) < 0)')\n self._prnt(' %s;' % errcode)\n self._prnt(' }')\n\n def _convert_expr_from_c(self, tp, var, context):\n if isinstance(tp, model.PrimitiveType):\n if tp.is_integer_type() and tp.name != '_Bool':\n return '_cffi_from_c_int(%s, %s)' % (var, tp.name)\n elif tp.name != 'long double':\n return '_cffi_from_c_%s(%s)' % (tp.name.replace(' ', '_'), var)\n else:\n return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (\n var, self._gettypenum(tp))\n elif isinstance(tp, (model.PointerType, model.FunctionPtrType)):\n return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (\n var, self._gettypenum(tp))\n elif isinstance(tp, model.ArrayType):\n return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (\n var, self._gettypenum(model.PointerType(tp.item)))\n elif isinstance(tp, model.StructOrUnion):\n if tp.fldnames is None:\n raise TypeError("'%s' is used as %s, but is opaque" % (\n tp._get_c_name(), context))\n return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % (\n var, self._gettypenum(tp))\n elif isinstance(tp, model.EnumType):\n return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (\n var, self._gettypenum(tp))\n else:\n raise NotImplementedError(tp)\n\n # ----------\n # typedefs: generates no code so far\n\n _generate_cpy_typedef_collecttype = _generate_nothing\n _generate_cpy_typedef_decl = _generate_nothing\n _generate_cpy_typedef_method = _generate_nothing\n _loading_cpy_typedef = _loaded_noop\n _loaded_cpy_typedef = _loaded_noop\n\n # ----------\n # function declarations\n\n def _generate_cpy_function_collecttype(self, tp, name):\n assert isinstance(tp, model.FunctionPtrType)\n if tp.ellipsis:\n self._do_collect_type(tp)\n else:\n # don't call _do_collect_type(tp) in this common case,\n # otherwise test_autofilled_struct_as_argument fails\n for type in tp.args:\n self._do_collect_type(type)\n self._do_collect_type(tp.result)\n\n def _generate_cpy_function_decl(self, tp, name):\n assert isinstance(tp, model.FunctionPtrType)\n if tp.ellipsis:\n # cannot support vararg functions better than this: check for its\n # exact type (including the fixed arguments), and build it as a\n # constant function pointer (no CPython wrapper)\n self._generate_cpy_const(False, name, tp)\n return\n prnt = self._prnt\n numargs = len(tp.args)\n if numargs == 0:\n argname = 'noarg'\n elif numargs == 1:\n argname = 'arg0'\n else:\n argname = 'args'\n prnt('static PyObject *')\n prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname))\n prnt('{')\n #\n context = 'argument of %s' % name\n for i, type in enumerate(tp.args):\n prnt(' %s;' % type.get_c_name(' x%d' % i, context))\n #\n localvars = set()\n freelines = set()\n for type in tp.args:\n self._extra_local_variables(type, localvars, freelines)\n for decl in sorted(localvars):\n prnt(' %s;' % (decl,))\n #\n if not isinstance(tp.result, model.VoidType):\n result_code = 'result = '\n context = 'result of %s' % name\n prnt(' %s;' % tp.result.get_c_name(' result', context))\n prnt(' PyObject *pyresult;')\n else:\n result_code = ''\n #\n if len(tp.args) > 1:\n rng = range(len(tp.args))\n for i in rng:\n prnt(' PyObject *arg%d;' % i)\n prnt()\n prnt(' if (!PyArg_ParseTuple(args, "%s:%s", %s))' % (\n 'O' * numargs, name, ', '.join(['&arg%d' % i for i in rng])))\n prnt(' return NULL;')\n prnt()\n #\n for i, type in enumerate(tp.args):\n self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i,\n 'return NULL')\n prnt()\n #\n prnt(' Py_BEGIN_ALLOW_THREADS')\n prnt(' _cffi_restore_errno();')\n prnt(' { %s%s(%s); }' % (\n result_code, name,\n ', '.join(['x%d' % i for i in range(len(tp.args))])))\n prnt(' _cffi_save_errno();')\n prnt(' Py_END_ALLOW_THREADS')\n prnt()\n #\n prnt(' (void)self; /* unused */')\n if numargs == 0:\n prnt(' (void)noarg; /* unused */')\n if result_code:\n prnt(' pyresult = %s;' %\n self._convert_expr_from_c(tp.result, 'result', 'result type'))\n for freeline in freelines:\n prnt(' ' + freeline)\n prnt(' return pyresult;')\n else:\n for freeline in freelines:\n prnt(' ' + freeline)\n prnt(' Py_INCREF(Py_None);')\n prnt(' return Py_None;')\n prnt('}')\n prnt()\n\n def _generate_cpy_function_method(self, tp, name):\n if tp.ellipsis:\n return\n numargs = len(tp.args)\n if numargs == 0:\n meth = 'METH_NOARGS'\n elif numargs == 1:\n meth = 'METH_O'\n else:\n meth = 'METH_VARARGS'\n self._prnt(' {"%s", _cffi_f_%s, %s, NULL},' % (name, name, meth))\n\n _loading_cpy_function = _loaded_noop\n\n def _loaded_cpy_function(self, tp, name, module, library):\n if tp.ellipsis:\n return\n func = getattr(module, name)\n setattr(library, name, func)\n self._types_of_builtin_functions[func] = tp\n\n # ----------\n # named structs\n\n _generate_cpy_struct_collecttype = _generate_nothing\n def _generate_cpy_struct_decl(self, tp, name):\n assert name == tp.name\n self._generate_struct_or_union_decl(tp, 'struct', name)\n def _generate_cpy_struct_method(self, tp, name):\n self._generate_struct_or_union_method(tp, 'struct', name)\n def _loading_cpy_struct(self, tp, name, module):\n self._loading_struct_or_union(tp, 'struct', name, module)\n def _loaded_cpy_struct(self, tp, name, module, **kwds):\n self._loaded_struct_or_union(tp)\n\n _generate_cpy_union_collecttype = _generate_nothing\n def _generate_cpy_union_decl(self, tp, name):\n assert name == tp.name\n self._generate_struct_or_union_decl(tp, 'union', name)\n def _generate_cpy_union_method(self, tp, name):\n self._generate_struct_or_union_method(tp, 'union', name)\n def _loading_cpy_union(self, tp, name, module):\n self._loading_struct_or_union(tp, 'union', name, module)\n def _loaded_cpy_union(self, tp, name, module, **kwds):\n self._loaded_struct_or_union(tp)\n\n def _generate_struct_or_union_decl(self, tp, prefix, name):\n if tp.fldnames is None:\n return # nothing to do with opaque structs\n checkfuncname = '_cffi_check_%s_%s' % (prefix, name)\n layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)\n cname = ('%s %s' % (prefix, name)).strip()\n #\n prnt = self._prnt\n prnt('static void %s(%s *p)' % (checkfuncname, cname))\n prnt('{')\n prnt(' /* only to generate compile-time warnings or errors */')\n prnt(' (void)p;')\n for fname, ftype, fbitsize, fqual in tp.enumfields():\n if (isinstance(ftype, model.PrimitiveType)\n and ftype.is_integer_type()) or fbitsize >= 0:\n # accept all integers, but complain on float or double\n prnt(' (void)((p->%s) << 1);' % fname)\n else:\n # only accept exactly the type declared.\n try:\n prnt(' { %s = &p->%s; (void)tmp; }' % (\n ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual),\n fname))\n except VerificationError as e:\n prnt(' /* %s */' % str(e)) # cannot verify it, ignore\n prnt('}')\n prnt('static PyObject *')\n prnt('%s(PyObject *self, PyObject *noarg)' % (layoutfuncname,))\n prnt('{')\n prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname)\n prnt(' static Py_ssize_t nums[] = {')\n prnt(' sizeof(%s),' % cname)\n prnt(' offsetof(struct _cffi_aligncheck, y),')\n for fname, ftype, fbitsize, fqual in tp.enumfields():\n if fbitsize >= 0:\n continue # xxx ignore fbitsize for now\n prnt(' offsetof(%s, %s),' % (cname, fname))\n if isinstance(ftype, model.ArrayType) and ftype.length is None:\n prnt(' 0, /* %s */' % ftype._get_c_name())\n else:\n prnt(' sizeof(((%s *)0)->%s),' % (cname, fname))\n prnt(' -1')\n prnt(' };')\n prnt(' (void)self; /* unused */')\n prnt(' (void)noarg; /* unused */')\n prnt(' return _cffi_get_struct_layout(nums);')\n prnt(' /* the next line is not executed, but compiled */')\n prnt(' %s(0);' % (checkfuncname,))\n prnt('}')\n prnt()\n\n def _generate_struct_or_union_method(self, tp, prefix, name):\n if tp.fldnames is None:\n return # nothing to do with opaque structs\n layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)\n self._prnt(' {"%s", %s, METH_NOARGS, NULL},' % (layoutfuncname,\n layoutfuncname))\n\n def _loading_struct_or_union(self, tp, prefix, name, module):\n if tp.fldnames is None:\n return # nothing to do with opaque structs\n layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)\n #\n function = getattr(module, layoutfuncname)\n layout = function()\n if isinstance(tp, model.StructOrUnion) and tp.partial:\n # use the function()'s sizes and offsets to guide the\n # layout of the struct\n totalsize = layout[0]\n totalalignment = layout[1]\n fieldofs = layout[2::2]\n fieldsize = layout[3::2]\n tp.force_flatten()\n assert len(fieldofs) == len(fieldsize) == len(tp.fldnames)\n tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment\n else:\n cname = ('%s %s' % (prefix, name)).strip()\n self._struct_pending_verification[tp] = layout, cname\n\n def _loaded_struct_or_union(self, tp):\n if tp.fldnames is None:\n return # nothing to do with opaque structs\n self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered\n\n if tp in self._struct_pending_verification:\n # check that the layout sizes and offsets match the real ones\n def check(realvalue, expectedvalue, msg):\n if realvalue != expectedvalue:\n raise VerificationError(\n "%s (we have %d, but C compiler says %d)"\n % (msg, expectedvalue, realvalue))\n ffi = self.ffi\n BStruct = ffi._get_cached_btype(tp)\n layout, cname = self._struct_pending_verification.pop(tp)\n check(layout[0], ffi.sizeof(BStruct), "wrong total size")\n check(layout[1], ffi.alignof(BStruct), "wrong total alignment")\n i = 2\n for fname, ftype, fbitsize, fqual in tp.enumfields():\n if fbitsize >= 0:\n continue # xxx ignore fbitsize for now\n check(layout[i], ffi.offsetof(BStruct, fname),\n "wrong offset for field %r" % (fname,))\n if layout[i+1] != 0:\n BField = ffi._get_cached_btype(ftype)\n check(layout[i+1], ffi.sizeof(BField),\n "wrong size for field %r" % (fname,))\n i += 2\n assert i == len(layout)\n\n # ----------\n # 'anonymous' declarations. These are produced for anonymous structs\n # or unions; the 'name' is obtained by a typedef.\n\n _generate_cpy_anonymous_collecttype = _generate_nothing\n\n def _generate_cpy_anonymous_decl(self, tp, name):\n if isinstance(tp, model.EnumType):\n self._generate_cpy_enum_decl(tp, name, '')\n else:\n self._generate_struct_or_union_decl(tp, '', name)\n\n def _generate_cpy_anonymous_method(self, tp, name):\n if not isinstance(tp, model.EnumType):\n self._generate_struct_or_union_method(tp, '', name)\n\n def _loading_cpy_anonymous(self, tp, name, module):\n if isinstance(tp, model.EnumType):\n self._loading_cpy_enum(tp, name, module)\n else:\n self._loading_struct_or_union(tp, '', name, module)\n\n def _loaded_cpy_anonymous(self, tp, name, module, **kwds):\n if isinstance(tp, model.EnumType):\n self._loaded_cpy_enum(tp, name, module, **kwds)\n else:\n self._loaded_struct_or_union(tp)\n\n # ----------\n # constants, likely declared with '#define'\n\n def _generate_cpy_const(self, is_int, name, tp=None, category='const',\n vartp=None, delayed=True, size_too=False,\n check_value=None):\n prnt = self._prnt\n funcname = '_cffi_%s_%s' % (category, name)\n prnt('static int %s(PyObject *lib)' % funcname)\n prnt('{')\n prnt(' PyObject *o;')\n prnt(' int res;')\n if not is_int:\n prnt(' %s;' % (vartp or tp).get_c_name(' i', name))\n else:\n assert category == 'const'\n #\n if check_value is not None:\n self._check_int_constant_value(name, check_value)\n #\n if not is_int:\n if category == 'var':\n realexpr = '&' + name\n else:\n realexpr = name\n prnt(' i = (%s);' % (realexpr,))\n prnt(' o = %s;' % (self._convert_expr_from_c(tp, 'i',\n 'variable type'),))\n assert delayed\n else:\n prnt(' o = _cffi_from_c_int_const(%s);' % name)\n prnt(' if (o == NULL)')\n prnt(' return -1;')\n if size_too:\n prnt(' {')\n prnt(' PyObject *o1 = o;')\n prnt(' o = Py_BuildValue("On", o1, (Py_ssize_t)sizeof(%s));'\n % (name,))\n prnt(' Py_DECREF(o1);')\n prnt(' if (o == NULL)')\n prnt(' return -1;')\n prnt(' }')\n prnt(' res = PyObject_SetAttrString(lib, "%s", o);' % name)\n prnt(' Py_DECREF(o);')\n prnt(' if (res < 0)')\n prnt(' return -1;')\n prnt(' return %s;' % self._chained_list_constants[delayed])\n self._chained_list_constants[delayed] = funcname + '(lib)'\n prnt('}')\n prnt()\n\n def _generate_cpy_constant_collecttype(self, tp, name):\n is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()\n if not is_int:\n self._do_collect_type(tp)\n\n def _generate_cpy_constant_decl(self, tp, name):\n is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()\n self._generate_cpy_const(is_int, name, tp)\n\n _generate_cpy_constant_method = _generate_nothing\n _loading_cpy_constant = _loaded_noop\n _loaded_cpy_constant = _loaded_noop\n\n # ----------\n # enums\n\n def _check_int_constant_value(self, name, value, err_prefix=''):\n prnt = self._prnt\n if value <= 0:\n prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % (\n name, name, value))\n else:\n prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % (\n name, name, value))\n prnt(' char buf[64];')\n prnt(' if ((%s) <= 0)' % name)\n prnt(' snprintf(buf, 63, "%%ld", (long)(%s));' % name)\n prnt(' else')\n prnt(' snprintf(buf, 63, "%%lu", (unsigned long)(%s));' %\n name)\n prnt(' PyErr_Format(_cffi_VerificationError,')\n prnt(' "%s%s has the real value %s, not %s",')\n prnt(' "%s", "%s", buf, "%d");' % (\n err_prefix, name, value))\n prnt(' return -1;')\n prnt(' }')\n\n def _enum_funcname(self, prefix, name):\n # "$enum_$1" => "___D_enum____D_1"\n name = name.replace('$', '___D_')\n return '_cffi_e_%s_%s' % (prefix, name)\n\n def _generate_cpy_enum_decl(self, tp, name, prefix='enum'):\n if tp.partial:\n for enumerator in tp.enumerators:\n self._generate_cpy_const(True, enumerator, delayed=False)\n return\n #\n funcname = self._enum_funcname(prefix, name)\n prnt = self._prnt\n prnt('static int %s(PyObject *lib)' % funcname)\n prnt('{')\n for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):\n self._check_int_constant_value(enumerator, enumvalue,\n "enum %s: " % name)\n prnt(' return %s;' % self._chained_list_constants[True])\n self._chained_list_constants[True] = funcname + '(lib)'\n prnt('}')\n prnt()\n\n _generate_cpy_enum_collecttype = _generate_nothing\n _generate_cpy_enum_method = _generate_nothing\n\n def _loading_cpy_enum(self, tp, name, module):\n if tp.partial:\n enumvalues = [getattr(module, enumerator)\n for enumerator in tp.enumerators]\n tp.enumvalues = tuple(enumvalues)\n tp.partial_resolved = True\n\n def _loaded_cpy_enum(self, tp, name, module, library):\n for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):\n setattr(library, enumerator, enumvalue)\n\n # ----------\n # macros: for now only for integers\n\n def _generate_cpy_macro_decl(self, tp, name):\n if tp == '...':\n check_value = None\n else:\n check_value = tp # an integer\n self._generate_cpy_const(True, name, check_value=check_value)\n\n _generate_cpy_macro_collecttype = _generate_nothing\n _generate_cpy_macro_method = _generate_nothing\n _loading_cpy_macro = _loaded_noop\n _loaded_cpy_macro = _loaded_noop\n\n # ----------\n # global variables\n\n def _generate_cpy_variable_collecttype(self, tp, name):\n if isinstance(tp, model.ArrayType):\n tp_ptr = model.PointerType(tp.item)\n else:\n tp_ptr = model.PointerType(tp)\n self._do_collect_type(tp_ptr)\n\n def _generate_cpy_variable_decl(self, tp, name):\n if isinstance(tp, model.ArrayType):\n tp_ptr = model.PointerType(tp.item)\n self._generate_cpy_const(False, name, tp, vartp=tp_ptr,\n size_too = tp.length_is_unknown())\n else:\n tp_ptr = model.PointerType(tp)\n self._generate_cpy_const(False, name, tp_ptr, category='var')\n\n _generate_cpy_variable_method = _generate_nothing\n _loading_cpy_variable = _loaded_noop\n\n def _loaded_cpy_variable(self, tp, name, module, library):\n value = getattr(library, name)\n if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the\n # sense that "a=..." is forbidden\n if tp.length_is_unknown():\n assert isinstance(value, tuple)\n (value, size) = value\n BItemType = self.ffi._get_cached_btype(tp.item)\n length, rest = divmod(size, self.ffi.sizeof(BItemType))\n if rest != 0:\n raise VerificationError(\n "bad size: %r does not seem to be an array of %s" %\n (name, tp.item))\n tp = tp.resolve_length(length)\n # 'value' is a <cdata 'type *'> which we have to replace with\n # a <cdata 'type[N]'> if the N is actually known\n if tp.length is not None:\n BArray = self.ffi._get_cached_btype(tp)\n value = self.ffi.cast(BArray, value)\n setattr(library, name, value)\n return\n # remove ptr=<cdata 'int *'> from the library instance, and replace\n # it by a property on the class, which reads/writes into ptr[0].\n ptr = value\n delattr(library, name)\n def getter(library):\n return ptr[0]\n def setter(library, value):\n ptr[0] = value\n setattr(type(library), name, property(getter, setter))\n type(library)._cffi_dir.append(name)\n\n # ----------\n\n def _generate_setup_custom(self):\n prnt = self._prnt\n prnt('static int _cffi_setup_custom(PyObject *lib)')\n prnt('{')\n prnt(' return %s;' % self._chained_list_constants[True])\n prnt('}')\n\ncffimod_header = r'''\n#include <Python.h>\n#include <stddef.h>\n\n/* this block of #ifs should be kept exactly identical between\n c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py\n and cffi/_cffi_include.h */\n#if defined(_MSC_VER)\n# include <malloc.h> /* for alloca() */\n# if _MSC_VER < 1600 /* MSVC < 2010 */\n typedef __int8 int8_t;\n typedef __int16 int16_t;\n typedef __int32 int32_t;\n typedef __int64 int64_t;\n typedef unsigned __int8 uint8_t;\n typedef unsigned __int16 uint16_t;\n typedef unsigned __int32 uint32_t;\n typedef unsigned __int64 uint64_t;\n typedef __int8 int_least8_t;\n typedef __int16 int_least16_t;\n typedef __int32 int_least32_t;\n typedef __int64 int_least64_t;\n typedef unsigned __int8 uint_least8_t;\n typedef unsigned __int16 uint_least16_t;\n typedef unsigned __int32 uint_least32_t;\n typedef unsigned __int64 uint_least64_t;\n typedef __int8 int_fast8_t;\n typedef __int16 int_fast16_t;\n typedef __int32 int_fast32_t;\n typedef __int64 int_fast64_t;\n typedef unsigned __int8 uint_fast8_t;\n typedef unsigned __int16 uint_fast16_t;\n typedef unsigned __int32 uint_fast32_t;\n typedef unsigned __int64 uint_fast64_t;\n typedef __int64 intmax_t;\n typedef unsigned __int64 uintmax_t;\n# else\n# include <stdint.h>\n# endif\n# if _MSC_VER < 1800 /* MSVC < 2013 */\n# ifndef __cplusplus\n typedef unsigned char _Bool;\n# endif\n# endif\n# define _cffi_float_complex_t _Fcomplex /* include <complex.h> for it */\n# define _cffi_double_complex_t _Dcomplex /* include <complex.h> for it */\n#else\n# include <stdint.h>\n# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)\n# include <alloca.h>\n# endif\n# define _cffi_float_complex_t float _Complex\n# define _cffi_double_complex_t double _Complex\n#endif\n\n#if PY_MAJOR_VERSION < 3\n# undef PyCapsule_CheckExact\n# undef PyCapsule_GetPointer\n# define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))\n# define PyCapsule_GetPointer(capsule, name) \\n (PyCObject_AsVoidPtr(capsule))\n#endif\n\n#if PY_MAJOR_VERSION >= 3\n# define PyInt_FromLong PyLong_FromLong\n#endif\n\n#define _cffi_from_c_double PyFloat_FromDouble\n#define _cffi_from_c_float PyFloat_FromDouble\n#define _cffi_from_c_long PyInt_FromLong\n#define _cffi_from_c_ulong PyLong_FromUnsignedLong\n#define _cffi_from_c_longlong PyLong_FromLongLong\n#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong\n#define _cffi_from_c__Bool PyBool_FromLong\n\n#define _cffi_to_c_double PyFloat_AsDouble\n#define _cffi_to_c_float PyFloat_AsDouble\n\n#define _cffi_from_c_int_const(x) \\n (((x) > 0) ? \\n ((unsigned long long)(x) <= (unsigned long long)LONG_MAX) ? \\n PyInt_FromLong((long)(x)) : \\n PyLong_FromUnsignedLongLong((unsigned long long)(x)) : \\n ((long long)(x) >= (long long)LONG_MIN) ? \\n PyInt_FromLong((long)(x)) : \\n PyLong_FromLongLong((long long)(x)))\n\n#define _cffi_from_c_int(x, type) \\n (((type)-1) > 0 ? /* unsigned */ \\n (sizeof(type) < sizeof(long) ? \\n PyInt_FromLong((long)x) : \\n sizeof(type) == sizeof(long) ? \\n PyLong_FromUnsignedLong((unsigned long)x) : \\n PyLong_FromUnsignedLongLong((unsigned long long)x)) : \\n (sizeof(type) <= sizeof(long) ? \\n PyInt_FromLong((long)x) : \\n PyLong_FromLongLong((long long)x)))\n\n#define _cffi_to_c_int(o, type) \\n ((type)( \\n sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \\n : (type)_cffi_to_c_i8(o)) : \\n sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \\n : (type)_cffi_to_c_i16(o)) : \\n sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \\n : (type)_cffi_to_c_i32(o)) : \\n sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \\n : (type)_cffi_to_c_i64(o)) : \\n (Py_FatalError("unsupported size for type " #type), (type)0)))\n\n#define _cffi_to_c_i8 \\n ((int(*)(PyObject *))_cffi_exports[1])\n#define _cffi_to_c_u8 \\n ((int(*)(PyObject *))_cffi_exports[2])\n#define _cffi_to_c_i16 \\n ((int(*)(PyObject *))_cffi_exports[3])\n#define _cffi_to_c_u16 \\n ((int(*)(PyObject *))_cffi_exports[4])\n#define _cffi_to_c_i32 \\n ((int(*)(PyObject *))_cffi_exports[5])\n#define _cffi_to_c_u32 \\n ((unsigned int(*)(PyObject *))_cffi_exports[6])\n#define _cffi_to_c_i64 \\n ((long long(*)(PyObject *))_cffi_exports[7])\n#define _cffi_to_c_u64 \\n ((unsigned long long(*)(PyObject *))_cffi_exports[8])\n#define _cffi_to_c_char \\n ((int(*)(PyObject *))_cffi_exports[9])\n#define _cffi_from_c_pointer \\n ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[10])\n#define _cffi_to_c_pointer \\n ((char *(*)(PyObject *, CTypeDescrObject *))_cffi_exports[11])\n#define _cffi_get_struct_layout \\n ((PyObject *(*)(Py_ssize_t[]))_cffi_exports[12])\n#define _cffi_restore_errno \\n ((void(*)(void))_cffi_exports[13])\n#define _cffi_save_errno \\n ((void(*)(void))_cffi_exports[14])\n#define _cffi_from_c_char \\n ((PyObject *(*)(char))_cffi_exports[15])\n#define _cffi_from_c_deref \\n ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[16])\n#define _cffi_to_c \\n ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[17])\n#define _cffi_from_c_struct \\n ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[18])\n#define _cffi_to_c_wchar_t \\n ((wchar_t(*)(PyObject *))_cffi_exports[19])\n#define _cffi_from_c_wchar_t \\n ((PyObject *(*)(wchar_t))_cffi_exports[20])\n#define _cffi_to_c_long_double \\n ((long double(*)(PyObject *))_cffi_exports[21])\n#define _cffi_to_c__Bool \\n ((_Bool(*)(PyObject *))_cffi_exports[22])\n#define _cffi_prepare_pointer_call_argument \\n ((Py_ssize_t(*)(CTypeDescrObject *, PyObject *, char **))_cffi_exports[23])\n#define _cffi_convert_array_from_object \\n ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[24])\n#define _CFFI_NUM_EXPORTS 25\n\ntypedef struct _ctypedescr CTypeDescrObject;\n\nstatic void *_cffi_exports[_CFFI_NUM_EXPORTS];\nstatic PyObject *_cffi_types, *_cffi_VerificationError;\n\nstatic int _cffi_setup_custom(PyObject *lib); /* forward */\n\nstatic PyObject *_cffi_setup(PyObject *self, PyObject *args)\n{\n PyObject *library;\n int was_alive = (_cffi_types != NULL);\n (void)self; /* unused */\n if (!PyArg_ParseTuple(args, "OOO", &_cffi_types, &_cffi_VerificationError,\n &library))\n return NULL;\n Py_INCREF(_cffi_types);\n Py_INCREF(_cffi_VerificationError);\n if (_cffi_setup_custom(library) < 0)\n return NULL;\n return PyBool_FromLong(was_alive);\n}\n\nunion _cffi_union_alignment_u {\n unsigned char m_char;\n unsigned short m_short;\n unsigned int m_int;\n unsigned long m_long;\n unsigned long long m_longlong;\n float m_float;\n double m_double;\n long double m_longdouble;\n};\n\nstruct _cffi_freeme_s {\n struct _cffi_freeme_s *next;\n union _cffi_union_alignment_u alignment;\n};\n\n#ifdef __GNUC__\n __attribute__((unused))\n#endif\nstatic int _cffi_convert_array_argument(CTypeDescrObject *ctptr, PyObject *arg,\n char **output_data, Py_ssize_t datasize,\n struct _cffi_freeme_s **freeme)\n{\n char *p;\n if (datasize < 0)\n return -1;\n\n p = *output_data;\n if (p == NULL) {\n struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc(\n offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize);\n if (fp == NULL)\n return -1;\n fp->next = *freeme;\n *freeme = fp;\n p = *output_data = (char *)&fp->alignment;\n }\n memset((void *)p, 0, (size_t)datasize);\n return _cffi_convert_array_from_object(p, ctptr, arg);\n}\n\n#ifdef __GNUC__\n __attribute__((unused))\n#endif\nstatic void _cffi_free_array_arguments(struct _cffi_freeme_s *freeme)\n{\n do {\n void *p = (void *)freeme;\n freeme = freeme->next;\n PyObject_Free(p);\n } while (freeme != NULL);\n}\n\nstatic int _cffi_init(void)\n{\n PyObject *module, *c_api_object = NULL;\n\n module = PyImport_ImportModule("_cffi_backend");\n if (module == NULL)\n goto failure;\n\n c_api_object = PyObject_GetAttrString(module, "_C_API");\n if (c_api_object == NULL)\n goto failure;\n if (!PyCapsule_CheckExact(c_api_object)) {\n PyErr_SetNone(PyExc_ImportError);\n goto failure;\n }\n memcpy(_cffi_exports, PyCapsule_GetPointer(c_api_object, "cffi"),\n _CFFI_NUM_EXPORTS * sizeof(void *));\n\n Py_DECREF(module);\n Py_DECREF(c_api_object);\n return 0;\n\n failure:\n Py_XDECREF(module);\n Py_XDECREF(c_api_object);\n return -1;\n}\n\n#define _cffi_type(num) ((CTypeDescrObject *)PyList_GET_ITEM(_cffi_types, num))\n\n/**********/\n'''\n
|
.venv\Lib\site-packages\cffi\vengine_cpy.py
|
vengine_cpy.py
|
Python
| 43,752 | 0.95 | 0.190959 | 0.187311 |
vue-tools
| 545 |
2025-02-26T21:54:57.519412
|
MIT
| false |
daf6eb10097ce2b765bbb5a4187998ff
|
#\n# DEPRECATED: implementation for ffi.verify()\n#\nimport sys, os\nimport types\n\nfrom . import model\nfrom .error import VerificationError\n\n\nclass VGenericEngine(object):\n _class_key = 'g'\n _gen_python_module = False\n\n def __init__(self, verifier):\n self.verifier = verifier\n self.ffi = verifier.ffi\n self.export_symbols = []\n self._struct_pending_verification = {}\n\n def patch_extension_kwds(self, kwds):\n # add 'export_symbols' to the dictionary. Note that we add the\n # list before filling it. When we fill it, it will thus also show\n # up in kwds['export_symbols'].\n kwds.setdefault('export_symbols', self.export_symbols)\n\n def find_module(self, module_name, path, so_suffixes):\n for so_suffix in so_suffixes:\n basename = module_name + so_suffix\n if path is None:\n path = sys.path\n for dirname in path:\n filename = os.path.join(dirname, basename)\n if os.path.isfile(filename):\n return filename\n\n def collect_types(self):\n pass # not needed in the generic engine\n\n def _prnt(self, what=''):\n self._f.write(what + '\n')\n\n def write_source_to_f(self):\n prnt = self._prnt\n # first paste some standard set of lines that are mostly '#include'\n prnt(cffimod_header)\n # then paste the C source given by the user, verbatim.\n prnt(self.verifier.preamble)\n #\n # call generate_gen_xxx_decl(), for every xxx found from\n # ffi._parser._declarations. This generates all the functions.\n self._generate('decl')\n #\n # on Windows, distutils insists on putting init_cffi_xyz in\n # 'export_symbols', so instead of fighting it, just give up and\n # give it one\n if sys.platform == 'win32':\n if sys.version_info >= (3,):\n prefix = 'PyInit_'\n else:\n prefix = 'init'\n modname = self.verifier.get_module_name()\n prnt("void %s%s(void) { }\n" % (prefix, modname))\n\n def load_library(self, flags=0):\n # import it with the CFFI backend\n backend = self.ffi._backend\n # needs to make a path that contains '/', on Posix\n filename = os.path.join(os.curdir, self.verifier.modulefilename)\n module = backend.load_library(filename, flags)\n #\n # call loading_gen_struct() to get the struct layout inferred by\n # the C compiler\n self._load(module, 'loading')\n\n # build the FFILibrary class and instance, this is a module subclass\n # because modules are expected to have usually-constant-attributes and\n # in PyPy this means the JIT is able to treat attributes as constant,\n # which we want.\n class FFILibrary(types.ModuleType):\n _cffi_generic_module = module\n _cffi_ffi = self.ffi\n _cffi_dir = []\n def __dir__(self):\n return FFILibrary._cffi_dir\n library = FFILibrary("")\n #\n # finally, call the loaded_gen_xxx() functions. This will set\n # up the 'library' object.\n self._load(module, 'loaded', library=library)\n return library\n\n def _get_declarations(self):\n lst = [(key, tp) for (key, (tp, qual)) in\n self.ffi._parser._declarations.items()]\n lst.sort()\n return lst\n\n def _generate(self, step_name):\n for name, tp in self._get_declarations():\n kind, realname = name.split(' ', 1)\n try:\n method = getattr(self, '_generate_gen_%s_%s' % (kind,\n step_name))\n except AttributeError:\n raise VerificationError(\n "not implemented in verify(): %r" % name)\n try:\n method(tp, realname)\n except Exception as e:\n model.attach_exception_info(e, name)\n raise\n\n def _load(self, module, step_name, **kwds):\n for name, tp in self._get_declarations():\n kind, realname = name.split(' ', 1)\n method = getattr(self, '_%s_gen_%s' % (step_name, kind))\n try:\n method(tp, realname, module, **kwds)\n except Exception as e:\n model.attach_exception_info(e, name)\n raise\n\n def _generate_nothing(self, tp, name):\n pass\n\n def _loaded_noop(self, tp, name, module, **kwds):\n pass\n\n # ----------\n # typedefs: generates no code so far\n\n _generate_gen_typedef_decl = _generate_nothing\n _loading_gen_typedef = _loaded_noop\n _loaded_gen_typedef = _loaded_noop\n\n # ----------\n # function declarations\n\n def _generate_gen_function_decl(self, tp, name):\n assert isinstance(tp, model.FunctionPtrType)\n if tp.ellipsis:\n # cannot support vararg functions better than this: check for its\n # exact type (including the fixed arguments), and build it as a\n # constant function pointer (no _cffi_f_%s wrapper)\n self._generate_gen_const(False, name, tp)\n return\n prnt = self._prnt\n numargs = len(tp.args)\n argnames = []\n for i, type in enumerate(tp.args):\n indirection = ''\n if isinstance(type, model.StructOrUnion):\n indirection = '*'\n argnames.append('%sx%d' % (indirection, i))\n context = 'argument of %s' % name\n arglist = [type.get_c_name(' %s' % arg, context)\n for type, arg in zip(tp.args, argnames)]\n tpresult = tp.result\n if isinstance(tpresult, model.StructOrUnion):\n arglist.insert(0, tpresult.get_c_name(' *r', context))\n tpresult = model.void_type\n arglist = ', '.join(arglist) or 'void'\n wrappername = '_cffi_f_%s' % name\n self.export_symbols.append(wrappername)\n if tp.abi:\n abi = tp.abi + ' '\n else:\n abi = ''\n funcdecl = ' %s%s(%s)' % (abi, wrappername, arglist)\n context = 'result of %s' % name\n prnt(tpresult.get_c_name(funcdecl, context))\n prnt('{')\n #\n if isinstance(tp.result, model.StructOrUnion):\n result_code = '*r = '\n elif not isinstance(tp.result, model.VoidType):\n result_code = 'return '\n else:\n result_code = ''\n prnt(' %s%s(%s);' % (result_code, name, ', '.join(argnames)))\n prnt('}')\n prnt()\n\n _loading_gen_function = _loaded_noop\n\n def _loaded_gen_function(self, tp, name, module, library):\n assert isinstance(tp, model.FunctionPtrType)\n if tp.ellipsis:\n newfunction = self._load_constant(False, tp, name, module)\n else:\n indirections = []\n base_tp = tp\n if (any(isinstance(typ, model.StructOrUnion) for typ in tp.args)\n or isinstance(tp.result, model.StructOrUnion)):\n indirect_args = []\n for i, typ in enumerate(tp.args):\n if isinstance(typ, model.StructOrUnion):\n typ = model.PointerType(typ)\n indirections.append((i, typ))\n indirect_args.append(typ)\n indirect_result = tp.result\n if isinstance(indirect_result, model.StructOrUnion):\n if indirect_result.fldtypes is None:\n raise TypeError("'%s' is used as result type, "\n "but is opaque" % (\n indirect_result._get_c_name(),))\n indirect_result = model.PointerType(indirect_result)\n indirect_args.insert(0, indirect_result)\n indirections.insert(0, ("result", indirect_result))\n indirect_result = model.void_type\n tp = model.FunctionPtrType(tuple(indirect_args),\n indirect_result, tp.ellipsis)\n BFunc = self.ffi._get_cached_btype(tp)\n wrappername = '_cffi_f_%s' % name\n newfunction = module.load_function(BFunc, wrappername)\n for i, typ in indirections:\n newfunction = self._make_struct_wrapper(newfunction, i, typ,\n base_tp)\n setattr(library, name, newfunction)\n type(library)._cffi_dir.append(name)\n\n def _make_struct_wrapper(self, oldfunc, i, tp, base_tp):\n backend = self.ffi._backend\n BType = self.ffi._get_cached_btype(tp)\n if i == "result":\n ffi = self.ffi\n def newfunc(*args):\n res = ffi.new(BType)\n oldfunc(res, *args)\n return res[0]\n else:\n def newfunc(*args):\n args = args[:i] + (backend.newp(BType, args[i]),) + args[i+1:]\n return oldfunc(*args)\n newfunc._cffi_base_type = base_tp\n return newfunc\n\n # ----------\n # named structs\n\n def _generate_gen_struct_decl(self, tp, name):\n assert name == tp.name\n self._generate_struct_or_union_decl(tp, 'struct', name)\n\n def _loading_gen_struct(self, tp, name, module):\n self._loading_struct_or_union(tp, 'struct', name, module)\n\n def _loaded_gen_struct(self, tp, name, module, **kwds):\n self._loaded_struct_or_union(tp)\n\n def _generate_gen_union_decl(self, tp, name):\n assert name == tp.name\n self._generate_struct_or_union_decl(tp, 'union', name)\n\n def _loading_gen_union(self, tp, name, module):\n self._loading_struct_or_union(tp, 'union', name, module)\n\n def _loaded_gen_union(self, tp, name, module, **kwds):\n self._loaded_struct_or_union(tp)\n\n def _generate_struct_or_union_decl(self, tp, prefix, name):\n if tp.fldnames is None:\n return # nothing to do with opaque structs\n checkfuncname = '_cffi_check_%s_%s' % (prefix, name)\n layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)\n cname = ('%s %s' % (prefix, name)).strip()\n #\n prnt = self._prnt\n prnt('static void %s(%s *p)' % (checkfuncname, cname))\n prnt('{')\n prnt(' /* only to generate compile-time warnings or errors */')\n prnt(' (void)p;')\n for fname, ftype, fbitsize, fqual in tp.enumfields():\n if (isinstance(ftype, model.PrimitiveType)\n and ftype.is_integer_type()) or fbitsize >= 0:\n # accept all integers, but complain on float or double\n prnt(' (void)((p->%s) << 1);' % fname)\n else:\n # only accept exactly the type declared.\n try:\n prnt(' { %s = &p->%s; (void)tmp; }' % (\n ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual),\n fname))\n except VerificationError as e:\n prnt(' /* %s */' % str(e)) # cannot verify it, ignore\n prnt('}')\n self.export_symbols.append(layoutfuncname)\n prnt('intptr_t %s(intptr_t i)' % (layoutfuncname,))\n prnt('{')\n prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname)\n prnt(' static intptr_t nums[] = {')\n prnt(' sizeof(%s),' % cname)\n prnt(' offsetof(struct _cffi_aligncheck, y),')\n for fname, ftype, fbitsize, fqual in tp.enumfields():\n if fbitsize >= 0:\n continue # xxx ignore fbitsize for now\n prnt(' offsetof(%s, %s),' % (cname, fname))\n if isinstance(ftype, model.ArrayType) and ftype.length is None:\n prnt(' 0, /* %s */' % ftype._get_c_name())\n else:\n prnt(' sizeof(((%s *)0)->%s),' % (cname, fname))\n prnt(' -1')\n prnt(' };')\n prnt(' return nums[i];')\n prnt(' /* the next line is not executed, but compiled */')\n prnt(' %s(0);' % (checkfuncname,))\n prnt('}')\n prnt()\n\n def _loading_struct_or_union(self, tp, prefix, name, module):\n if tp.fldnames is None:\n return # nothing to do with opaque structs\n layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)\n #\n BFunc = self.ffi._typeof_locked("intptr_t(*)(intptr_t)")[0]\n function = module.load_function(BFunc, layoutfuncname)\n layout = []\n num = 0\n while True:\n x = function(num)\n if x < 0: break\n layout.append(x)\n num += 1\n if isinstance(tp, model.StructOrUnion) and tp.partial:\n # use the function()'s sizes and offsets to guide the\n # layout of the struct\n totalsize = layout[0]\n totalalignment = layout[1]\n fieldofs = layout[2::2]\n fieldsize = layout[3::2]\n tp.force_flatten()\n assert len(fieldofs) == len(fieldsize) == len(tp.fldnames)\n tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment\n else:\n cname = ('%s %s' % (prefix, name)).strip()\n self._struct_pending_verification[tp] = layout, cname\n\n def _loaded_struct_or_union(self, tp):\n if tp.fldnames is None:\n return # nothing to do with opaque structs\n self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered\n\n if tp in self._struct_pending_verification:\n # check that the layout sizes and offsets match the real ones\n def check(realvalue, expectedvalue, msg):\n if realvalue != expectedvalue:\n raise VerificationError(\n "%s (we have %d, but C compiler says %d)"\n % (msg, expectedvalue, realvalue))\n ffi = self.ffi\n BStruct = ffi._get_cached_btype(tp)\n layout, cname = self._struct_pending_verification.pop(tp)\n check(layout[0], ffi.sizeof(BStruct), "wrong total size")\n check(layout[1], ffi.alignof(BStruct), "wrong total alignment")\n i = 2\n for fname, ftype, fbitsize, fqual in tp.enumfields():\n if fbitsize >= 0:\n continue # xxx ignore fbitsize for now\n check(layout[i], ffi.offsetof(BStruct, fname),\n "wrong offset for field %r" % (fname,))\n if layout[i+1] != 0:\n BField = ffi._get_cached_btype(ftype)\n check(layout[i+1], ffi.sizeof(BField),\n "wrong size for field %r" % (fname,))\n i += 2\n assert i == len(layout)\n\n # ----------\n # 'anonymous' declarations. These are produced for anonymous structs\n # or unions; the 'name' is obtained by a typedef.\n\n def _generate_gen_anonymous_decl(self, tp, name):\n if isinstance(tp, model.EnumType):\n self._generate_gen_enum_decl(tp, name, '')\n else:\n self._generate_struct_or_union_decl(tp, '', name)\n\n def _loading_gen_anonymous(self, tp, name, module):\n if isinstance(tp, model.EnumType):\n self._loading_gen_enum(tp, name, module, '')\n else:\n self._loading_struct_or_union(tp, '', name, module)\n\n def _loaded_gen_anonymous(self, tp, name, module, **kwds):\n if isinstance(tp, model.EnumType):\n self._loaded_gen_enum(tp, name, module, **kwds)\n else:\n self._loaded_struct_or_union(tp)\n\n # ----------\n # constants, likely declared with '#define'\n\n def _generate_gen_const(self, is_int, name, tp=None, category='const',\n check_value=None):\n prnt = self._prnt\n funcname = '_cffi_%s_%s' % (category, name)\n self.export_symbols.append(funcname)\n if check_value is not None:\n assert is_int\n assert category == 'const'\n prnt('int %s(char *out_error)' % funcname)\n prnt('{')\n self._check_int_constant_value(name, check_value)\n prnt(' return 0;')\n prnt('}')\n elif is_int:\n assert category == 'const'\n prnt('int %s(long long *out_value)' % funcname)\n prnt('{')\n prnt(' *out_value = (long long)(%s);' % (name,))\n prnt(' return (%s) <= 0;' % (name,))\n prnt('}')\n else:\n assert tp is not None\n assert check_value is None\n if category == 'var':\n ampersand = '&'\n else:\n ampersand = ''\n extra = ''\n if category == 'const' and isinstance(tp, model.StructOrUnion):\n extra = 'const *'\n ampersand = '&'\n prnt(tp.get_c_name(' %s%s(void)' % (extra, funcname), name))\n prnt('{')\n prnt(' return (%s%s);' % (ampersand, name))\n prnt('}')\n prnt()\n\n def _generate_gen_constant_decl(self, tp, name):\n is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()\n self._generate_gen_const(is_int, name, tp)\n\n _loading_gen_constant = _loaded_noop\n\n def _load_constant(self, is_int, tp, name, module, check_value=None):\n funcname = '_cffi_const_%s' % name\n if check_value is not None:\n assert is_int\n self._load_known_int_constant(module, funcname)\n value = check_value\n elif is_int:\n BType = self.ffi._typeof_locked("long long*")[0]\n BFunc = self.ffi._typeof_locked("int(*)(long long*)")[0]\n function = module.load_function(BFunc, funcname)\n p = self.ffi.new(BType)\n negative = function(p)\n value = int(p[0])\n if value < 0 and not negative:\n BLongLong = self.ffi._typeof_locked("long long")[0]\n value += (1 << (8*self.ffi.sizeof(BLongLong)))\n else:\n assert check_value is None\n fntypeextra = '(*)(void)'\n if isinstance(tp, model.StructOrUnion):\n fntypeextra = '*' + fntypeextra\n BFunc = self.ffi._typeof_locked(tp.get_c_name(fntypeextra, name))[0]\n function = module.load_function(BFunc, funcname)\n value = function()\n if isinstance(tp, model.StructOrUnion):\n value = value[0]\n return value\n\n def _loaded_gen_constant(self, tp, name, module, library):\n is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()\n value = self._load_constant(is_int, tp, name, module)\n setattr(library, name, value)\n type(library)._cffi_dir.append(name)\n\n # ----------\n # enums\n\n def _check_int_constant_value(self, name, value):\n prnt = self._prnt\n if value <= 0:\n prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % (\n name, name, value))\n else:\n prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % (\n name, name, value))\n prnt(' char buf[64];')\n prnt(' if ((%s) <= 0)' % name)\n prnt(' sprintf(buf, "%%ld", (long)(%s));' % name)\n prnt(' else')\n prnt(' sprintf(buf, "%%lu", (unsigned long)(%s));' %\n name)\n prnt(' sprintf(out_error, "%s has the real value %s, not %s",')\n prnt(' "%s", buf, "%d");' % (name[:100], value))\n prnt(' return -1;')\n prnt(' }')\n\n def _load_known_int_constant(self, module, funcname):\n BType = self.ffi._typeof_locked("char[]")[0]\n BFunc = self.ffi._typeof_locked("int(*)(char*)")[0]\n function = module.load_function(BFunc, funcname)\n p = self.ffi.new(BType, 256)\n if function(p) < 0:\n error = self.ffi.string(p)\n if sys.version_info >= (3,):\n error = str(error, 'utf-8')\n raise VerificationError(error)\n\n def _enum_funcname(self, prefix, name):\n # "$enum_$1" => "___D_enum____D_1"\n name = name.replace('$', '___D_')\n return '_cffi_e_%s_%s' % (prefix, name)\n\n def _generate_gen_enum_decl(self, tp, name, prefix='enum'):\n if tp.partial:\n for enumerator in tp.enumerators:\n self._generate_gen_const(True, enumerator)\n return\n #\n funcname = self._enum_funcname(prefix, name)\n self.export_symbols.append(funcname)\n prnt = self._prnt\n prnt('int %s(char *out_error)' % funcname)\n prnt('{')\n for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):\n self._check_int_constant_value(enumerator, enumvalue)\n prnt(' return 0;')\n prnt('}')\n prnt()\n\n def _loading_gen_enum(self, tp, name, module, prefix='enum'):\n if tp.partial:\n enumvalues = [self._load_constant(True, tp, enumerator, module)\n for enumerator in tp.enumerators]\n tp.enumvalues = tuple(enumvalues)\n tp.partial_resolved = True\n else:\n funcname = self._enum_funcname(prefix, name)\n self._load_known_int_constant(module, funcname)\n\n def _loaded_gen_enum(self, tp, name, module, library):\n for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):\n setattr(library, enumerator, enumvalue)\n type(library)._cffi_dir.append(enumerator)\n\n # ----------\n # macros: for now only for integers\n\n def _generate_gen_macro_decl(self, tp, name):\n if tp == '...':\n check_value = None\n else:\n check_value = tp # an integer\n self._generate_gen_const(True, name, check_value=check_value)\n\n _loading_gen_macro = _loaded_noop\n\n def _loaded_gen_macro(self, tp, name, module, library):\n if tp == '...':\n check_value = None\n else:\n check_value = tp # an integer\n value = self._load_constant(True, tp, name, module,\n check_value=check_value)\n setattr(library, name, value)\n type(library)._cffi_dir.append(name)\n\n # ----------\n # global variables\n\n def _generate_gen_variable_decl(self, tp, name):\n if isinstance(tp, model.ArrayType):\n if tp.length_is_unknown():\n prnt = self._prnt\n funcname = '_cffi_sizeof_%s' % (name,)\n self.export_symbols.append(funcname)\n prnt("size_t %s(void)" % funcname)\n prnt("{")\n prnt(" return sizeof(%s);" % (name,))\n prnt("}")\n tp_ptr = model.PointerType(tp.item)\n self._generate_gen_const(False, name, tp_ptr)\n else:\n tp_ptr = model.PointerType(tp)\n self._generate_gen_const(False, name, tp_ptr, category='var')\n\n _loading_gen_variable = _loaded_noop\n\n def _loaded_gen_variable(self, tp, name, module, library):\n if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the\n # sense that "a=..." is forbidden\n if tp.length_is_unknown():\n funcname = '_cffi_sizeof_%s' % (name,)\n BFunc = self.ffi._typeof_locked('size_t(*)(void)')[0]\n function = module.load_function(BFunc, funcname)\n size = function()\n BItemType = self.ffi._get_cached_btype(tp.item)\n length, rest = divmod(size, self.ffi.sizeof(BItemType))\n if rest != 0:\n raise VerificationError(\n "bad size: %r does not seem to be an array of %s" %\n (name, tp.item))\n tp = tp.resolve_length(length)\n tp_ptr = model.PointerType(tp.item)\n value = self._load_constant(False, tp_ptr, name, module)\n # 'value' is a <cdata 'type *'> which we have to replace with\n # a <cdata 'type[N]'> if the N is actually known\n if tp.length is not None:\n BArray = self.ffi._get_cached_btype(tp)\n value = self.ffi.cast(BArray, value)\n setattr(library, name, value)\n type(library)._cffi_dir.append(name)\n return\n # remove ptr=<cdata 'int *'> from the library instance, and replace\n # it by a property on the class, which reads/writes into ptr[0].\n funcname = '_cffi_var_%s' % name\n BFunc = self.ffi._typeof_locked(tp.get_c_name('*(*)(void)', name))[0]\n function = module.load_function(BFunc, funcname)\n ptr = function()\n def getter(library):\n return ptr[0]\n def setter(library, value):\n ptr[0] = value\n setattr(type(library), name, property(getter, setter))\n type(library)._cffi_dir.append(name)\n\ncffimod_header = r'''\n#include <stdio.h>\n#include <stddef.h>\n#include <stdarg.h>\n#include <errno.h>\n#include <sys/types.h> /* XXX for ssize_t on some platforms */\n\n/* this block of #ifs should be kept exactly identical between\n c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py\n and cffi/_cffi_include.h */\n#if defined(_MSC_VER)\n# include <malloc.h> /* for alloca() */\n# if _MSC_VER < 1600 /* MSVC < 2010 */\n typedef __int8 int8_t;\n typedef __int16 int16_t;\n typedef __int32 int32_t;\n typedef __int64 int64_t;\n typedef unsigned __int8 uint8_t;\n typedef unsigned __int16 uint16_t;\n typedef unsigned __int32 uint32_t;\n typedef unsigned __int64 uint64_t;\n typedef __int8 int_least8_t;\n typedef __int16 int_least16_t;\n typedef __int32 int_least32_t;\n typedef __int64 int_least64_t;\n typedef unsigned __int8 uint_least8_t;\n typedef unsigned __int16 uint_least16_t;\n typedef unsigned __int32 uint_least32_t;\n typedef unsigned __int64 uint_least64_t;\n typedef __int8 int_fast8_t;\n typedef __int16 int_fast16_t;\n typedef __int32 int_fast32_t;\n typedef __int64 int_fast64_t;\n typedef unsigned __int8 uint_fast8_t;\n typedef unsigned __int16 uint_fast16_t;\n typedef unsigned __int32 uint_fast32_t;\n typedef unsigned __int64 uint_fast64_t;\n typedef __int64 intmax_t;\n typedef unsigned __int64 uintmax_t;\n# else\n# include <stdint.h>\n# endif\n# if _MSC_VER < 1800 /* MSVC < 2013 */\n# ifndef __cplusplus\n typedef unsigned char _Bool;\n# endif\n# endif\n# define _cffi_float_complex_t _Fcomplex /* include <complex.h> for it */\n# define _cffi_double_complex_t _Dcomplex /* include <complex.h> for it */\n#else\n# include <stdint.h>\n# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)\n# include <alloca.h>\n# endif\n# define _cffi_float_complex_t float _Complex\n# define _cffi_double_complex_t double _Complex\n#endif\n'''\n
|
.venv\Lib\site-packages\cffi\vengine_gen.py
|
vengine_gen.py
|
Python
| 26,939 | 0.95 | 0.235641 | 0.142395 |
react-lib
| 361 |
2023-12-05T21:27:17.427196
|
BSD-3-Clause
| false |
1cb6605c045da47463d53561ac8fbcc2
|
#ifndef CFFI_MESSAGEBOX\n# ifdef _MSC_VER\n# define CFFI_MESSAGEBOX 1\n# else\n# define CFFI_MESSAGEBOX 0\n# endif\n#endif\n\n\n#if CFFI_MESSAGEBOX\n/* Windows only: logic to take the Python-CFFI embedding logic\n initialization errors and display them in a background thread\n with MessageBox. The idea is that if the whole program closes\n as a result of this problem, then likely it is already a console\n program and you can read the stderr output in the console too.\n If it is not a console program, then it will likely show its own\n dialog to complain, or generally not abruptly close, and for this\n case the background thread should stay alive.\n*/\nstatic void *volatile _cffi_bootstrap_text;\n\nstatic PyObject *_cffi_start_error_capture(void)\n{\n PyObject *result = NULL;\n PyObject *x, *m, *bi;\n\n if (InterlockedCompareExchangePointer(&_cffi_bootstrap_text,\n (void *)1, NULL) != NULL)\n return (PyObject *)1;\n\n m = PyImport_AddModule("_cffi_error_capture");\n if (m == NULL)\n goto error;\n\n result = PyModule_GetDict(m);\n if (result == NULL)\n goto error;\n\n#if PY_MAJOR_VERSION >= 3\n bi = PyImport_ImportModule("builtins");\n#else\n bi = PyImport_ImportModule("__builtin__");\n#endif\n if (bi == NULL)\n goto error;\n PyDict_SetItemString(result, "__builtins__", bi);\n Py_DECREF(bi);\n\n x = PyRun_String(\n "import sys\n"\n "class FileLike:\n"\n " def write(self, x):\n"\n " try:\n"\n " of.write(x)\n"\n " except: pass\n"\n " self.buf += x\n"\n " def flush(self):\n"\n " pass\n"\n "fl = FileLike()\n"\n "fl.buf = ''\n"\n "of = sys.stderr\n"\n "sys.stderr = fl\n"\n "def done():\n"\n " sys.stderr = of\n"\n " return fl.buf\n", /* make sure the returned value stays alive */\n Py_file_input,\n result, result);\n Py_XDECREF(x);\n\n error:\n if (PyErr_Occurred())\n {\n PyErr_WriteUnraisable(Py_None);\n PyErr_Clear();\n }\n return result;\n}\n\n#pragma comment(lib, "user32.lib")\n\nstatic DWORD WINAPI _cffi_bootstrap_dialog(LPVOID ignored)\n{\n Sleep(666); /* may be interrupted if the whole process is closing */\n#if PY_MAJOR_VERSION >= 3\n MessageBoxW(NULL, (wchar_t *)_cffi_bootstrap_text,\n L"Python-CFFI error",\n MB_OK | MB_ICONERROR);\n#else\n MessageBoxA(NULL, (char *)_cffi_bootstrap_text,\n "Python-CFFI error",\n MB_OK | MB_ICONERROR);\n#endif\n _cffi_bootstrap_text = NULL;\n return 0;\n}\n\nstatic void _cffi_stop_error_capture(PyObject *ecap)\n{\n PyObject *s;\n void *text;\n\n if (ecap == (PyObject *)1)\n return;\n\n if (ecap == NULL)\n goto error;\n\n s = PyRun_String("done()", Py_eval_input, ecap, ecap);\n if (s == NULL)\n goto error;\n\n /* Show a dialog box, but in a background thread, and\n never show multiple dialog boxes at once. */\n#if PY_MAJOR_VERSION >= 3\n text = PyUnicode_AsWideCharString(s, NULL);\n#else\n text = PyString_AsString(s);\n#endif\n\n _cffi_bootstrap_text = text;\n\n if (text != NULL)\n {\n HANDLE h;\n h = CreateThread(NULL, 0, _cffi_bootstrap_dialog,\n NULL, 0, NULL);\n if (h != NULL)\n CloseHandle(h);\n }\n /* decref the string, but it should stay alive as 'fl.buf'\n in the small module above. It will really be freed only if\n we later get another similar error. So it's a leak of at\n most one copy of the small module. That's fine for this\n situation which is usually a "fatal error" anyway. */\n Py_DECREF(s);\n PyErr_Clear();\n return;\n\n error:\n _cffi_bootstrap_text = NULL;\n PyErr_Clear();\n}\n\n#else\n\nstatic PyObject *_cffi_start_error_capture(void) { return NULL; }\nstatic void _cffi_stop_error_capture(PyObject *ecap) { }\n\n#endif\n
|
.venv\Lib\site-packages\cffi\_cffi_errors.h
|
_cffi_errors.h
|
C
| 3,908 | 0.95 | 0.161074 | 0.188976 |
awesome-app
| 416 |
2023-07-27T12:56:06.959591
|
Apache-2.0
| false |
64efe54b03e5ae3a4da6775598600f51
|
\ntry:\n # this works on Python < 3.12\n from imp import *\n\nexcept ImportError:\n # this is a limited emulation for Python >= 3.12.\n # Note that this is used only for tests or for the old ffi.verify().\n # This is copied from the source code of Python 3.11.\n\n from _imp import (acquire_lock, release_lock,\n is_builtin, is_frozen)\n\n from importlib._bootstrap import _load\n\n from importlib import machinery\n import os\n import sys\n import tokenize\n\n SEARCH_ERROR = 0\n PY_SOURCE = 1\n PY_COMPILED = 2\n C_EXTENSION = 3\n PY_RESOURCE = 4\n PKG_DIRECTORY = 5\n C_BUILTIN = 6\n PY_FROZEN = 7\n PY_CODERESOURCE = 8\n IMP_HOOK = 9\n\n def get_suffixes():\n extensions = [(s, 'rb', C_EXTENSION)\n for s in machinery.EXTENSION_SUFFIXES]\n source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]\n bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]\n return extensions + source + bytecode\n\n def find_module(name, path=None):\n if not isinstance(name, str):\n raise TypeError("'name' must be a str, not {}".format(type(name)))\n elif not isinstance(path, (type(None), list)):\n # Backwards-compatibility\n raise RuntimeError("'path' must be None or a list, "\n "not {}".format(type(path)))\n\n if path is None:\n if is_builtin(name):\n return None, None, ('', '', C_BUILTIN)\n elif is_frozen(name):\n return None, None, ('', '', PY_FROZEN)\n else:\n path = sys.path\n\n for entry in path:\n package_directory = os.path.join(entry, name)\n for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:\n package_file_name = '__init__' + suffix\n file_path = os.path.join(package_directory, package_file_name)\n if os.path.isfile(file_path):\n return None, package_directory, ('', '', PKG_DIRECTORY)\n for suffix, mode, type_ in get_suffixes():\n file_name = name + suffix\n file_path = os.path.join(entry, file_name)\n if os.path.isfile(file_path):\n break\n else:\n continue\n break # Break out of outer loop when breaking out of inner loop.\n else:\n raise ImportError(name, name=name)\n\n encoding = None\n if 'b' not in mode:\n with open(file_path, 'rb') as file:\n encoding = tokenize.detect_encoding(file.readline)[0]\n file = open(file_path, mode, encoding=encoding)\n return file, file_path, (suffix, mode, type_)\n\n def load_dynamic(name, path, file=None):\n loader = machinery.ExtensionFileLoader(name, path)\n spec = machinery.ModuleSpec(name=name, loader=loader, origin=path)\n return _load(spec)\n
|
.venv\Lib\site-packages\cffi\_imp_emulation.py
|
_imp_emulation.py
|
Python
| 2,960 | 0.95 | 0.228916 | 0.070423 |
vue-tools
| 227 |
2024-08-27T08:49:09.833282
|
Apache-2.0
| false |
e84849d59d243dfc32ddf6992db2e5c5
|
"""\nTemporary shim module to indirect the bits of distutils we need from setuptools/distutils while providing useful\nerror messages beyond `No module named 'distutils' on Python >= 3.12, or when setuptools' vendored distutils is broken.\n\nThis is a compromise to avoid a hard-dep on setuptools for Python >= 3.12, since many users don't need runtime compilation support from CFFI.\n"""\nimport sys\n\ntry:\n # import setuptools first; this is the most robust way to ensure its embedded distutils is available\n # (the .pth shim should usually work, but this is even more robust)\n import setuptools\nexcept Exception as ex:\n if sys.version_info >= (3, 12):\n # Python 3.12 has no built-in distutils to fall back on, so any import problem is fatal\n raise Exception("This CFFI feature requires setuptools on Python >= 3.12. The setuptools module is missing or non-functional.") from ex\n\n # silently ignore on older Pythons (support fallback to stdlib distutils where available)\nelse:\n del setuptools\n\ntry:\n # bring in just the bits of distutils we need, whether they really came from setuptools or stdlib-embedded distutils\n from distutils import log, sysconfig\n from distutils.ccompiler import CCompiler\n from distutils.command.build_ext import build_ext\n from distutils.core import Distribution, Extension\n from distutils.dir_util import mkpath\n from distutils.errors import DistutilsSetupError, CompileError, LinkError\n from distutils.log import set_threshold, set_verbosity\n\n if sys.platform == 'win32':\n try:\n # FUTURE: msvc9compiler module was removed in setuptools 74; consider removing, as it's only used by an ancient patch in `recompiler`\n from distutils.msvc9compiler import MSVCCompiler\n except ImportError:\n MSVCCompiler = None\nexcept Exception as ex:\n if sys.version_info >= (3, 12):\n raise Exception("This CFFI feature requires setuptools on Python >= 3.12. Please install the setuptools package.") from ex\n\n # anything older, just let the underlying distutils import error fly\n raise Exception("This CFFI feature requires distutils. Please install the distutils or setuptools package.") from ex\n\ndel sys\n
|
.venv\Lib\site-packages\cffi\_shimmed_dist_utils.py
|
_shimmed_dist_utils.py
|
Python
| 2,230 | 0.95 | 0.177778 | 0.184211 |
react-lib
| 459 |
2024-01-29T01:49:07.316295
|
GPL-3.0
| false |
8fc51e95b05afee467430862d9d15a0a
|
__all__ = ['FFI', 'VerificationError', 'VerificationMissing', 'CDefError',\n 'FFIError']\n\nfrom .api import FFI\nfrom .error import CDefError, FFIError, VerificationError, VerificationMissing\nfrom .error import PkgConfigError\n\n__version__ = "1.17.1"\n__version_info__ = (1, 17, 1)\n\n# The verifier module file names are based on the CRC32 of a string that\n# contains the following version number. It may be older than __version__\n# if nothing is clearly incompatible.\n__version_verifier_modules__ = "0.8.6"\n
|
.venv\Lib\site-packages\cffi\__init__.py
|
__init__.py
|
Python
| 513 | 0.95 | 0.071429 | 0.272727 |
react-lib
| 875 |
2024-05-11T18:16:50.948488
|
GPL-3.0
| false |
73a106798b33aaf7607639ef38601110
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\api.cpython-313.pyc
|
api.cpython-313.pyc
|
Other
| 49,992 | 0.95 | 0.068041 | 0.006652 |
python-kit
| 620 |
2024-10-30T02:53:32.559806
|
BSD-3-Clause
| false |
f13c818ebe921f5e0f8c5ceba82fb7d7
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\backend_ctypes.cpython-313.pyc
|
backend_ctypes.cpython-313.pyc
|
Other
| 64,505 | 0.75 | 0.015385 | 0.024048 |
python-kit
| 90 |
2024-01-21T17:13:13.220777
|
BSD-3-Clause
| false |
6114bac05be597a9ac74532ea96fe096
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\cffi_opcode.cpython-313.pyc
|
cffi_opcode.cpython-313.pyc
|
Other
| 6,938 | 0.8 | 0 | 0 |
awesome-app
| 860 |
2024-08-11T12:26:30.866688
|
MIT
| false |
349199db20df8a4198af5c8239c32d9c
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\commontypes.cpython-313.pyc
|
commontypes.cpython-313.pyc
|
Other
| 3,117 | 0.8 | 0.022222 | 0.025641 |
node-utils
| 540 |
2024-10-04T08:48:59.079770
|
BSD-3-Clause
| false |
88f596a235e0935187a3f41703344756
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\cparser.cpython-313.pyc
|
cparser.cpython-313.pyc
|
Other
| 48,098 | 0.95 | 0.028571 | 0.020134 |
awesome-app
| 958 |
2025-02-18T03:31:47.987339
|
Apache-2.0
| false |
980ee9737e1ff463857a2cd613404811
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\error.cpython-313.pyc
|
error.cpython-313.pyc
|
Other
| 2,030 | 0.8 | 0.047619 | 0 |
node-utils
| 331 |
2023-12-22T06:02:31.655196
|
BSD-3-Clause
| false |
0945e1efe52caa3844dd329673e6a6ee
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\ffiplatform.cpython-313.pyc
|
ffiplatform.cpython-313.pyc
|
Other
| 5,909 | 0.8 | 0 | 0 |
node-utils
| 459 |
2024-07-14T21:00:45.501471
|
Apache-2.0
| false |
97c094681a0e392abd80f378a9c0223a
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\lock.cpython-313.pyc
|
lock.cpython-313.pyc
|
Other
| 525 | 0.7 | 0 | 0 |
vue-tools
| 401 |
2024-05-11T13:08:35.967106
|
Apache-2.0
| false |
1c5139223c2b8afa64734e511749ac3f
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\model.cpython-313.pyc
|
model.cpython-313.pyc
|
Other
| 30,889 | 0.95 | 0.011811 | 0.00823 |
python-kit
| 864 |
2024-06-28T08:26:06.334996
|
Apache-2.0
| false |
adf7158823334a12a322109ef0f6f7f0
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\pkgconfig.cpython-313.pyc
|
pkgconfig.cpython-313.pyc
|
Other
| 6,513 | 0.8 | 0.048387 | 0 |
vue-tools
| 628 |
2025-04-12T14:17:23.113950
|
BSD-3-Clause
| false |
890124a6bb087ab2fe2c94a4a0fda0a2
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\recompiler.cpython-313.pyc
|
recompiler.cpython-313.pyc
|
Other
| 82,686 | 0.75 | 0.019802 | 0.021314 |
python-kit
| 725 |
2025-01-01T20:39:13.204682
|
GPL-3.0
| false |
58b1d6e013089ee2ee893dd54610d14e
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\setuptools_ext.cpython-313.pyc
|
setuptools_ext.cpython-313.pyc
|
Other
| 10,979 | 0.8 | 0.037736 | 0 |
vue-tools
| 689 |
2024-12-25T13:26:15.566629
|
GPL-3.0
| false |
404cca2cbf7c32ab5c5cb365d698b966
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\vengine_cpy.cpython-313.pyc
|
vengine_cpy.cpython-313.pyc
|
Other
| 51,474 | 0.95 | 0.052161 | 0.13141 |
vue-tools
| 577 |
2024-01-14T03:43:36.067183
|
GPL-3.0
| false |
591191295d4e5f6a34d4441a8921839d
|
\n\n
|
.venv\Lib\site-packages\cffi\__pycache__\vengine_gen.cpython-313.pyc
|
vengine_gen.cpython-313.pyc
|
Other
| 34,575 | 0.95 | 0.045161 | 0.106312 |
python-kit
| 565 |
2025-01-29T04:47:33.136882
|
BSD-3-Clause
| false |
b864e51ddf19670be0e06521f13bb115
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.