diff --git a/setup.py b/setup.py index 4caf46f5..3183763a 100644 --- a/setup.py +++ b/setup.py @@ -4,6 +4,7 @@ 'redis>=4.5.4;python_version >= "3.0"', 'redis>=3.5.3;python_version < "3.0"', 'redis-dump-load', + 'fakeredis', ] high_performance_deps = [ diff --git a/src/swsssdk/configdb.py b/src/swsssdk/configdb.py index 95aeb2ba..0ba2bcf7 100644 --- a/src/swsssdk/configdb.py +++ b/src/swsssdk/configdb.py @@ -392,9 +392,10 @@ def __mod_entry(self, pipe, table, key, data): else: pipe.hmset(_hash, self.typed_to_raw(data)) - def mod_config(self, data): + def mod_config(self, data, table_delete=None): """Write multiple tables into config db. Extra entries/fields in the db which are not in the data are kept. + Pass one or more tables in table_delete to delete tables before update. Args: data: config data in a dictionary form { @@ -402,9 +403,16 @@ def mod_config(self, data): 'MULTI_KEY_TABLE_NAME': { ('l1_key', 'l2_key', ...) : {'column_key': 'value', ...}, ...}, ... } + table_delete: Table name(s) that will be deleted first before modify """ client = self.get_redis_client(self.db_name) pipe = client.pipeline() + if table_delete: + if isinstance(table_delete, list): + for t in table_delete: + self.__delete_table(client, pipe, t) + else: + self.__delete_table(client, pipe, table_delete) for table_name in data: table_data = data[table_name] if table_data is None: diff --git a/test/test_configdb.py b/test/test_configdb.py new file mode 100644 index 00000000..1123f046 --- /dev/null +++ b/test/test_configdb.py @@ -0,0 +1,31 @@ +import os +import sys + +from unittest import mock + +from unittest import TestCase + +modules_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(modules_path, 'src')) + +import swsssdk +import fakeredis + + +class TestConfigDB(TestCase): + def test__configdb_pipe(self): + + s_db = swsssdk.ConfigDBPipeConnector() + #Use fakeredis to mock redis db + r_db = fakeredis.FakeStrictRedis(version=5) + s_db.get_redis_client = lambda db_name: r_db + s_db.db_name = "CONFIG_DB" + + s_db.mod_config({'TABLE_NAME': { 'row_key': {'column_key1': 'valueA1', 'column_key2': 'valueB1'}}}) + self.assertEqual(r_db.hget('TABLE_NAME|row_key', 'column_key1'), b'valueA1') + self.assertEqual(r_db.hget('TABLE_NAME|row_key', 'column_key2'), b'valueB1') + s_db.mod_config({'TABLE_NAME': { 'row_key': {'column_key1': 'valueA2'}}}, table_delete='TABLE_NAME') + self.assertEqual(r_db.hget('TABLE_NAME|row_key', 'column_key1'), b'valueA2') + self.assertEqual(r_db.hget('TABLE_NAME|row_key', 'column_key2'), None) + +