How to write test cases by Unit test for database configuration file? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to write test cases by Unit test for database configuration file? (/thread-24529.html) |
How to write test cases by Unit test for database configuration file? - binhduonggttn - Feb-18-2020 I have a yaml file containing database configuration information and a python file to check connect to database via that configuration file. Then I writed some test cases in python file. There's a Function def test_db_type_postgres(self): database = DB({'database': 'postgres'}); self.assertEqual(database.get_db_type(), 'postgres')I hope the above function is that if the database is Postgres then it will pass, but it failed. I checked Test Log. It seems that it is affected by method #checking db option dbopt = self.__get_dbopt() if dbopt is None: raise InvalidConfigError( 'E01002', 'Invalid database options.') else: self.dbopt = dboptWhere am I wrong? Please show me. Any help is appreciated. My python file (include test cases): import yaml import unittest class InvalidConfigError(Exception): pass class DB(): def __init__(self, dbconf): self._dbconf = dict(dbconf) # checking for database type dbtype = self.get_db_type() if dbtype != 'sqlite' and dbtype != 'postgres': raise InvalidConfigError() else: self.dbtype = dbtype #checking db option dbopt = self.__get_dbopt() if dbopt is None: raise InvalidConfigError( 'E01002', 'Invalid database options.') else: self.dbopt = dbopt def get_db_type(self): return self._dbconf.get('database') def __get_dbopt(self): return self._dbconf.get('dbopt') class TestDBtype(unittest.TestCase): #setUpClass gets calls only once where as setUp gets called before every test @classmethod def setUpClass(cls): cls.init_db() @classmethod def init_db(cls): with open('DatabaseConfig.yml') as f: data = yaml.full_load(f) for item, doc in data.items(): print(item, ":", doc) cls.database = DB(data) def test_missing_db(self): database = DB({'database': None}); self.assertRaises(InvalidConfigError) def test_db_type_postgres(self): database = DB({'database': 'postgres'}); self.assertEqual(database.get_db_type(), 'postgres') def test_db_type_invalid(self): database = DB({'database': 'mysql'}); self.assertRaises(InvalidConfigError) class TestOpt(unittest.TestCase): #setUpClass gets calls only once where as setUp gets called before every test @classmethod def setUpClass(cls): cls.init_db() @classmethod def init_db(cls): with open('DatabaseConfig.yml') as f: data = yaml.full_load(f) for item, doc in data.items(): print(item, ":", doc) cls.database = DB(data) def test_db_opt(self): database = DB({'dbopt': None}); self.assertRaises(InvalidConfigError) if __name__ == '__main__': unittest.main()Test log ouput:
|