Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何通过单元测试测试else函数?_Python 3.x_Unit Testing_Pyyaml - Fatal编程技术网

Python 3.x 如何通过单元测试测试else函数?

Python 3.x 如何通过单元测试测试else函数?,python-3.x,unit-testing,pyyaml,Python 3.x,Unit Testing,Pyyaml,我有一个YAML配置文件,用于检查与数据库的连接。我需要为我的配置文件编写一些测试用例,包括几个场景: 如果数据库字段为空,则测试用例失败。 如果数据库不是Sqlite或Postgre,测试用例将失败。 我已经创建了一个测试类,但我不知道如何实现它。有人能给我提个建议吗 数据_source.yml: database: dbopt: host: bvcbvcbvcb.com port: 5432 dbname: db1 user: username passwo

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

如果数据库字段为空,则测试用例失败。 如果数据库不是Sqlite或Postgre,测试用例将失败。 我已经创建了一个测试类,但我不知道如何实现它。有人能给我提个建议吗

数据_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

数据_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()


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

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