【问题标题】:Python unit tests: type checking custom class typePython单元测试:类型检查自定义类类型
【发布时间】:2015-07-27 21:06:28
【问题描述】:

我在开发程序时正在编写单元测试。我将 SQLAlchemy 用于数据库进程,所以我有一些这样的函数:

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

如果我做print(type(engine)),我可以看到类型是<class 'sqlalchemy.engine.base.Engine'>

...所以我想通过检查类型是否正确来测试此功能是否有效(假设如果create_engine 调用失败,则类型将为None...)

此代码在unittests.py:

class TestDatabase(unittest.TestCase):


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

如何检查 class 变量的类型?

【问题讨论】:

    标签: python unit-testing types sqlalchemy


    【解决方案1】:

    这里有几个选项...最简单的就是检查你返回的对象不是None

    self.assertIsNotNone(myprogram_database.create_sqla_engine())
    

    如果你真的想检查返回类型是否是其他东西的实例,你可以使用assertIsInstance

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 2013-01-29
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多