Python Forum
How to write test cases by Unit test for database configuration file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to write test cases by Unit test for database configuration file?
#1
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 = dbopt
Where am I wrong? Please show me. Any help is appreciated.
[Image: uYiW9.png]

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:
Error:
database : postgres dbopt : {'host': 'localhost', 'port': 6311, 'dbname': 'spam_eggs', 'user': 'hamburger', 'password': 'example_password', 'client_encoding': 'utf-8', 'connect_timeout': 60, 'sslmode': 'none'} query : select * from manufacturing_product test_db_type_invalid (test_db_type.TestDBtype) ... ERROR NoneType: None test_db_type_postgres (test_db_type.TestDBtype) ... ERROR NoneType: None test_missing_db (test_db_type.TestDBtype) ... ERROR NoneType: None ====================================================================== ERROR: test_db_type_invalid (test_db_type.TestDBtype) ---------------------------------------------------------------------- Traceback (most recent call last): File "d:\Python\TestDataSource\test_db_type.py", line 60, in test_db_type_invalid database = DB({'database': 'mysql'}); File "d:\Python\TestDataSource\test_db_type.py", line 14, in __init__ raise InvalidConfigError() test_db_type.InvalidConfigError ====================================================================== ERROR: test_db_type_postgres (test_db_type.TestDBtype) ---------------------------------------------------------------------- Traceback (most recent call last): File "d:\Python\TestDataSource\test_db_type.py", line 56, in test_db_type_postgres database = DB({'database': 'postgres'}); File "d:\Python\TestDataSource\test_db_type.py", line 22, in __init__ 'E01002', 'Invalid database options.') test_db_type.InvalidConfigError: ('E01002', 'Invalid database options.') ====================================================================== ERROR: test_missing_db (test_db_type.TestDBtype) ---------------------------------------------------------------------- Traceback (most recent call last): File "d:\Python\TestDataSource\test_db_type.py", line 52, in test_missing_db database = DB({'database': None}); File "d:\Python\TestDataSource\test_db_type.py", line 14, in __init__ raise InvalidConfigError() test_db_type.InvalidConfigError ---------------------------------------------------------------------- Ran 3 tests in 0.003s FAILED (errors=3)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Photo how I write the output into xml file in python? 3lnyn0 1 262 Oct-31-2021, 05:40 PM
Last Post: Gribouillis
  rows from sql query need to write to a file as columns sjcsvatt 6 416 Oct-09-2021, 12:45 AM
Last Post: snippsat
  Can't write to file Mark17 2 354 Sep-24-2021, 03:45 PM
Last Post: Mark17
Thumbs Up [SOLVED] Simplify condition test in if block? Winfried 2 390 Aug-25-2021, 09:42 PM
Last Post: Winfried
  How to write in text file - indented block Joni_Engr 3 599 Aug-09-2021, 06:30 PM
Last Post: deanhystad
  How to test and import a model form computer to test accuracy using Sklearn library Anldra12 6 899 Jul-03-2021, 10:07 AM
Last Post: Anldra12
  Read and write active Excel file euras 4 762 Jun-29-2021, 11:16 PM
Last Post: Pedroski55
  Find factor to match test curve to golden curve SriRajesh 0 464 Jun-17-2021, 04:39 AM
Last Post: SriRajesh
  Read file, reformat and write new file bryanmartin113 1 767 Jun-08-2021, 09:27 PM
Last Post: Larz60+
  How do I split a dataset into test/train/validation according to a particular group? 69195Student 1 706 May-12-2021, 08:27 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020