I have a YAML config file used to check connection to database. I need to write some test cases for my config file includes several scenarios :
I have created a test class but I don't know how to implement it. Can anyone suggest to me ?
data_source.yml:
database:
dbopt:
host: bvcbvcbvcb.com
port: 5432
dbname: db1
user: username
password: 1234
client_encoding: utf-8
connect_timeout: 60
sslmode: none
query:
select * from manufacturing_product
data_source.py:
import yaml
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(
'E01001', 'Invalid database type, should be sqlite or postgres.')
else:
self.dbtype = dbtype
def get_db_type(self):
return self._dbconf['database']
with open('data_source.yml') as f:
data = yaml.full_load(f)
for item, doc in data.items():
print(item, ":", doc)
database = DB(data)
My test class:
import yaml
import unittest
import data_source
class TestDBtype(unittest.TestCase):
def test_missing_db(self):
# if database is None then failed
# What should I do?
pass
def test_db_type(self):
# if database is not Sqlite or Postgres then failed
# What should I do?
pass
if __name__ == '__main__':
unittest.main()
You can use like below. Idea is to initialize DB once and use the connection instance in test cases. I have not tested, but this is the idea.
import data_source
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):
self.db_instance = data_source.DB( config_file )
def test_missing_db(self):
self.assertEqual( db_instance, None, "Connection returned None.")