| 217 | assert a == b == c == d |
| 218 | |
| 219 | def test_box_from_keys_protocol_object(self): |
| 220 | # dict() and Box.update() read anything with keys() and item access as a mapping; so does Box() |
| 221 | import sqlite3 |
| 222 | |
| 223 | db = sqlite3.connect(":memory:") |
| 224 | db.row_factory = sqlite3.Row |
| 225 | db.execute("create table t (name text, code text, n integer)") |
| 226 | db.execute("insert into t values ('ab', 'cd', 3)") |
| 227 | row = db.execute("select * from t").fetchone() |
| 228 | assert not isinstance(row, Mapping) |
| 229 | assert Box(row) == dict(row) == {"name": "ab", "code": "cd", "n": 3} |
| 230 | assert Box(row).name == "ab" |
| 231 | assert Box(row, extra=1) == {"name": "ab", "code": "cd", "n": 3, "extra": 1} |
| 232 | |
| 233 | # update() and merge_update() take the same objects, as dict.update does; iterating a Row yields |
| 234 | # its values, so they must go by keys() |
| 235 | updated = Box(extra=1) |
| 236 | updated.update(row) |
| 237 | assert updated == {"extra": 1, "name": "ab", "code": "cd", "n": 3} |
| 238 | merged = Box(extra=1) |
| 239 | merged.merge_update(row) |
| 240 | assert merged == updated |
| 241 | with pytest.raises(TypeError): # as dict | row: the operator takes a dict only |
| 242 | Box(extra=1) | row # noqa: B018 |
| 243 | config = ConfigBox(extra=1) |
| 244 | config.update(row) |
| 245 | assert config == updated |
| 246 | |
| 247 | class KeysOnly: |
| 248 | data = {"a": 1, "b": {"c": 2}} |
| 249 | |
| 250 | def keys(self): |
| 251 | return self.data.keys() |
| 252 | |
| 253 | def __getitem__(self, key): |
| 254 | return self.data[key] |
| 255 | |
| 256 | bx = Box(KeysOnly()) |
| 257 | assert bx == KeysOnly.data |
| 258 | assert bx.b.c == 2 |
| 259 | |
| 260 | class BadKeys(KeysOnly): |
| 261 | def keys(self): |
| 262 | return ["a", "missing"] |
| 263 | |
| 264 | with pytest.raises(KeyError): |
| 265 | Box(BadKeys()) |
| 266 | |
| 267 | def test_bad_inits(self): |
| 268 | with pytest.raises(ValueError): |