|
| 1 | +# |
| 2 | +# This test file attempts to verify function / method annotations are |
| 3 | +# correct, so try NOT to add any type-ignores to this file. |
| 4 | +# |
| 5 | + |
| 6 | +import sys |
| 7 | + |
| 8 | +import pytest |
| 9 | +import typeguard |
| 10 | +from lxml.etree import ( |
| 11 | + LXML_VERSION, |
| 12 | + Comment, |
| 13 | + Element, |
| 14 | + ElementTree, |
| 15 | + QName as QName, |
| 16 | + _Element, |
| 17 | + _ElementTree, |
| 18 | +) |
| 19 | + |
| 20 | +if sys.version_info >= (3, 11): |
| 21 | + from typing import reveal_type |
| 22 | +else: |
| 23 | + from typing_extensions import reveal_type |
| 24 | + |
| 25 | + |
| 26 | +class TestElementFactory: |
| 27 | + # lxml.etree.is_element() exists, but we want to test the |
| 28 | + # then-factory Element class instead of _Element |
| 29 | + def _is_element_check(self, el: Element) -> None: |
| 30 | + reveal_type(el) |
| 31 | + if LXML_VERSION >= (6, 0, 0): |
| 32 | + assert isinstance(el, Element) |
| 33 | + else: |
| 34 | + assert isinstance(el, _Element) |
| 35 | + if type(el) is not _Element: |
| 36 | + # TODO revealtype injector needs to support functiontype |
| 37 | + with pytest.raises(typeguard.TypeCheckError): |
| 38 | + reveal_type(el.tag) |
| 39 | + else: |
| 40 | + reveal_type(el.tag) |
| 41 | + |
| 42 | + def test_normal_element(self) -> None: |
| 43 | + el = Element("test") |
| 44 | + self._is_element_check(el) |
| 45 | + |
| 46 | + def test_comment_element(self) -> None: |
| 47 | + comm = Comment("test") |
| 48 | + self._is_element_check(comm) |
| 49 | + |
| 50 | + |
| 51 | +class TestElementTreeGeneric: |
| 52 | + def test_normal_tree(self, xml2_tree: ElementTree) -> None: |
| 53 | + reveal_type(xml2_tree) |
| 54 | + if LXML_VERSION >= (6, 0, 0): |
| 55 | + assert isinstance(xml2_tree, ElementTree) |
| 56 | + else: |
| 57 | + assert isinstance(xml2_tree, _ElementTree) |
| 58 | + # TODO need to write a typeguard plugin to support |
| 59 | + # checking elements within ElementTree |
| 60 | + |
| 61 | + # TODO write test to check that ElementTree[int] or other |
| 62 | + # non-element types are rejected by typeguard |
0 commit comments