Skip to content

Commit

Permalink
add test for dict2namedtuple
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielYang59 committed Nov 13, 2024
1 parent 9b11922 commit ecf19a5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
8 changes: 4 additions & 4 deletions src/monty/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,11 +216,11 @@ def dict2namedtuple(*args, **kwargs) -> tuple:
Helper function to create a class `namedtuple` from a dictionary.
Examples:
>>> t = dict2namedtuple(foo=1, bar="hello")
>>> assert t.foo == 1 and t.bar == "hello"
>>> tpl = dict2namedtuple(foo=1, bar="hello")
>>> assert tpl.foo == 1 and tpl.bar == "hello"
>>> t = dict2namedtuple([("foo", 1), ("bar", "hello")])
>>> assert t[0] == t.foo and t[1] == t.bar
>>> tpl = dict2namedtuple([("foo", 1), ("bar", "hello")])
>>> assert tpl[0] is tpl.foo and t[1] is tpl.bar
Warnings:
- The order of the items in the namedtuple is not deterministic if
Expand Down
34 changes: 32 additions & 2 deletions tests/test_collections.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
from __future__ import annotations

import os
from collections import namedtuple

import pytest

from monty.collections import AttrDict, FrozenAttrDict, Namespace, frozendict, tree
from monty.collections import (
AttrDict,
FrozenAttrDict,
Namespace,
dict2namedtuple,
frozendict,
tree,
)

TEST_DIR = os.path.join(os.path.dirname(__file__), "test_files")

Expand All @@ -30,14 +38,16 @@ def test_frozendict():


def test_namespace_dict():
dct = Namespace(foo="bar")
dct = Namespace(key="val")
dct["hello"] = "world"
assert dct["key"] == "val"

with pytest.raises(KeyError, match="Cannot overwrite existing key"):
dct["key"] = "val"
with pytest.raises(KeyError, match="Cannot overwrite existing key"):
dct.update({"key": "val"})
with pytest.raises(KeyError, match="Cannot overwrite existing key"):
dct |= {"key": "val"}


def test_attr_dict():
Expand All @@ -62,3 +72,23 @@ def test_frozen_attrdict():
# Test modifying existing item
with pytest.raises(KeyError, match="You cannot modify attribute"):
dct.hello = "new"
with pytest.raises(KeyError, match="You cannot modify attribute"):
dct["hello"] = "new"


def test_mongo_dict():
"""TODO: add test"""


def test_dict2namedtuple():
# Init from dict
tpl = dict2namedtuple(foo=1, bar="hello")
assert isinstance(tpl, tuple)
assert tpl.foo == 1 and tpl.bar == "hello"

# Init from list of tuples
tpl = dict2namedtuple([("foo", 1), ("bar", "hello")])
assert isinstance(tpl, tuple)
assert tpl[0] == 1
assert tpl[1] == "hello"
assert tpl[0] is tpl.foo and tpl[1] is tpl.bar

0 comments on commit ecf19a5

Please sign in to comment.