如何通过单元测试测试其他功能?



我有一个用于检查与数据库的连接的 YAML 配置文件。我需要为我的配置文件编写一些测试用例,包括几个场景:

  1. 如果数据库字段为空,则测试用例失败。
  2. 如果数据库不是 Sqlite 或 Postgre,则测试用例将失败。

我创建了一个测试类,但我不知道如何实现它。谁能向我建议?

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()

你可以像下面这样使用。想法是初始化一次数据库并在测试用例中使用连接实例。我没有测试过,但这就是想法。

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.")

最新更新