Python unit tests: type checking of a custom type

I write unit tests when I develop a program. I am using SQLAlchemy for database processes, so I have several functions like this:

def create_sqla_engine():
    """ Create and return the SQLA engine """
    mysql_uri = os.environ.get('MYSQL_CONNECTION_URI')
    engine = sqlalchemy.create_engine(mysql_uri)
    return engine

      

If I do print(type(engine))

, I see that the type<class 'sqlalchemy.engine.base.Engine'>

... so I want to test if this function works by checking the correctness of the type (assuming that the type will be None

if the call create_engine

fails ...)

This code is in unittests.py

:

class TestDatabase(unittest.TestCase):


    def test_database_create_merkle_sqla_session(self):
        assert type(myprogram_database.create_sqla_engine()) is # ?

      

How can I check the type of a variable class

?

+3


source to share


1 answer


You have several options here ... The simplest is to check that the returned object is not None

:

self.assertIsNotNone(myprogram_database.create_sqla_engine())

      



If you really want to check that the return type is an instance of something else, you can use assertIsInstance

:

self.assertIsInstance(myprogram_database.create_sqla_engine(),
                      sqlalchemy.engine.base.Engine)

      

+6


source







All Articles