aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBonfaceKilz2021-06-02 07:54:35 +0300
committerBonfaceKilz2021-06-03 21:58:31 +0300
commitbd952d23a523a25d014676912cfc1e174435f606 (patch)
tree3bf25f7c63d6881a5a1955d29e1b1c38f8ccf987
parentcd0f1155d2b325aa0863268d4e27397ae34afdec (diff)
downloadgenenetwork3-bd952d23a523a25d014676912cfc1e174435f606.tar.gz
Get the diff between 2 dicts and return that as a dict
-rw-r--r--gn3/db/__init__.py16
-rw-r--r--tests/unit/db/test_phenotypes.py8
2 files changed, 24 insertions, 0 deletions
diff --git a/gn3/db/__init__.py b/gn3/db/__init__.py
index 1eb7b12..19135fc 100644
--- a/gn3/db/__init__.py
+++ b/gn3/db/__init__.py
@@ -68,3 +68,19 @@ def fetchone(conn: Any,
with conn.cursor() as cursor:
cursor.execute(sql)
return DATACLASSMAP[table](*cursor.fetchone())
+
+
+def diff_from_dict(old: Dict, new: Dict) -> Dict:
+ """Construct a new dict with a specific structure that contains the difference
+between the 2 dicts in the structure:
+
+diff_from_dict({"id": 1, "data": "a"}, {"id": 2, "data": "b"})
+
+Should return:
+
+{"id": {"old": 1, "new": 2}, "data": {"old": "a", "new": "b"}}
+ """
+ dict_ = {}
+ for key, value in old.items():
+ dict_[key] = {"old": old[key], "new": new[key]}
+ return dict_
diff --git a/tests/unit/db/test_phenotypes.py b/tests/unit/db/test_phenotypes.py
index 505714a..b53db23 100644
--- a/tests/unit/db/test_phenotypes.py
+++ b/tests/unit/db/test_phenotypes.py
@@ -4,6 +4,7 @@ from unittest import mock
from gn3.db import fetchone
from gn3.db import update
+from gn3.db import diff_from_dict
from gn3.db.phenotypes import Phenotype
@@ -63,3 +64,10 @@ class TestPhenotypes(TestCase):
"Test pre-publication")
cursor.execute.assert_called_once_with(
"SELECT * FROM Phenotype WHERE id = '35'")
+
+ def test_diff_from_dict(self):
+ """Test that a correct diff is generated"""
+ self.assertEqual(diff_from_dict({"id": 1, "data": "a"},
+ {"id": 2, "data": "b"}),
+ {"id": {"old": 1, "new": 2},
+ "data": {"old": "a", "new": "b"}})