我有一个YAML配置文件,用于检查与数据库的连接。我需要为我的配置文件编写一些测试用例,其中包括几种方案:
我已经创建了一个测试类,但是我不知道如何实现它。有人可以建议我吗?
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)
我的考试班:
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()
答案 0 :(得分:0)
您可以像下面那样使用。想法是一次初始化数据库,并在测试用例中使用连接实例。我还没有测试,但这是个主意。
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.")