Skip to content

Commit

Permalink
TagAttributes: Implements proper comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
funkyfuture committed Jan 15, 2024
1 parent 56372b5 commit aaec117
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
17 changes: 17 additions & 0 deletions _delb/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,23 @@ def __init__(self, node: TagNode):
def __contains__(self, item: Any) -> bool:
return self[item] is not None

def __eq__(self, other: Any) -> bool:
if not isinstance(other, Mapping):
return False

if len(self) != len(other):
return False

if isinstance(other, TagAttributes):
for key, value in self.items():
assert isinstance(value, Attribute)
other_value = other[value.namespace : value.local_name] # type: ignore
if (other_value is None) or (value != other_value):
return False
return True

return self.as_dict_with_strings() == other

def __delitem__(self, key: str | slice):
if isinstance(key, str):
pass
Expand Down
48 changes: 48 additions & 0 deletions tests/test_attributes.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from textwrap import dedent

import pytest

from delb import new_tag_node, Document, InvalidOperation
Expand Down Expand Up @@ -60,6 +62,52 @@ def test_attribute_object():
attribute.value = "obsolete"


def test_comparison():
document = Document(
dedent(
"""\
<root>
<a xml:id="x"/>
<b id="x"/>
<c id="x"/>
<d id="x" od="y"/>
<p:e xmlns:p="https://u.rl" p:id="x" p:od="y"/>
</root>
"""
)
)
a = document.css_select("a").first
b = document.css_select("b").first
c = document.css_select("c").first
d = document.css_select("d").first
e = document.css_select("p|e", namespaces={"p": "https://u.rl"}).first

assert a.attributes == a.attributes
assert a.attributes != b.attributes
assert a.attributes != c.attributes
assert a.attributes != d.attributes
assert a.attributes != e.attributes
assert a.attributes == {"{http://www.w3.org/XML/1998/namespace}id": "x"}

assert b.attributes == b.attributes
assert b.attributes == c.attributes
assert b.attributes != d.attributes
assert b.attributes != e.attributes
assert b.attributes == {"id": "x"}

assert c.attributes == c.attributes
assert c.attributes != d.attributes
assert c.attributes != e.attributes
assert c.attributes == {"id": "x"}

assert d.attributes == d.attributes
assert d.attributes != e.attributes
assert d.attributes == {"od": "y", "id": "x"}

assert e.attributes == e.attributes
assert e.attributes == {"{https://u.rl}od": "y", "{https://u.rl}id": "x"}


def test_delete_namespaced_attribute():
root = Document('<root><node xmlns:p="ns" p:a="1" p:b="2"/></root>').root
node = root.css_select("node").first
Expand Down

0 comments on commit aaec117

Please sign in to comment.