corrscope/tests/test_model_bind.py

90 wiersze
2.3 KiB
Python
Czysty Zwykły widok Historia

2018-09-03 11:52:38 +00:00
import pytest
2019-03-07 06:21:18 +00:00
from corrscope.gui.model_bind import rgetattr, rsetattr, rhasattr, flatten_attr
2019-02-10 05:40:53 +00:00
class Person(object):
def __init__(self):
self.pet = Pet()
self.residence = Residence()
class Pet(object):
def __init__(self, name="Fido", species="Dog"):
self.name = name
self.species = species
class Residence(object):
def __init__(self, type="House", sqft=None):
self.type = type
self.sqft = sqft
2018-09-03 11:52:38 +00:00
def test_rgetattr():
""" Test to ensure recursive model access works.
GUI elements are named "prefix__" "recursive__attr" and bind to recursive.attr.
https://stackoverflow__com/a/31174427/
"""
p = Person()
# Test rgetattr(present)
2019-01-03 08:57:30 +00:00
assert rgetattr(p, "pet__species") == "Dog"
assert rgetattr(p, "pet__species", object()) == "Dog"
2018-09-03 11:52:38 +00:00
# Test rgetattr(missing)
2019-01-03 08:57:30 +00:00
assert rgetattr(p, "pet__ghost__species", "calico") == "calico"
2018-09-03 11:52:38 +00:00
with pytest.raises(AttributeError):
# Without a default argument, `rgetattr`, like `getattr`, raises
# AttributeError when the dotted attribute is missing
2019-01-03 08:57:30 +00:00
print(rgetattr(p, "pet__ghost__species"))
2018-09-03 11:52:38 +00:00
# Test rsetattr()
2019-01-03 08:57:30 +00:00
rsetattr(p, "pet__name", "Sparky")
rsetattr(p, "residence__type", "Apartment")
assert p.pet.name == "Sparky"
assert p.residence.type == "Apartment"
2018-09-03 11:52:38 +00:00
# Test rhasattr()
2019-01-03 08:57:30 +00:00
assert rhasattr(p, "pet")
assert rhasattr(p, "pet__name")
2018-09-03 11:52:38 +00:00
# Test rhasattr(levels of missing)
2019-01-03 08:57:30 +00:00
assert not rhasattr(p, "pet__ghost")
assert not rhasattr(p, "pet__ghost__species")
assert not rhasattr(p, "ghost")
assert not rhasattr(p, "ghost__species")
2019-02-10 05:40:53 +00:00
def test_flatten_attr():
p = Person()
# Test nested
flat, name = flatten_attr(p, "pet__name")
assert flat is p.pet
assert name == "name"
# Test 1 level
flat, name = flatten_attr(p, "pet")
assert flat is p
assert name == "pet"
def test_rgetattr_broken():
"""
rgetattr(default) fails to short-circuit/return on the first missing attribute.
I never use rgetattr(default) so I won't bother fixing the bug.
Wrong answer:
- None.foo AKA 1
- 1.bar AKA 1
- 1.imag == 0
Right answer:
- None.foo AKA return 1 to caller
"""
2019-02-05 08:54:35 +00:00
result = rgetattr(object(), "nothing__imag", 1)
assert result == 1, result