首页 > 解决方案 > AssertionError:“'str' 对象没有属性 'get'”

问题描述

我是 Python 新手。我有一个class DatabaseConfig包含数据库配置的一些信息。我使用 Unittest 编写了一个测试用例,脚本是 if dboptis invalid (say 'dbopt' : 'abc') then expected output is Throw exception: Invalid value {} of parameter 'dbopt'

但它失败了,我得到了错误:'str' object has no attribute 'get'。我不知道为什么。它应该已经过去了。有人能告诉我如何解决吗?谢谢你。

我的数据库配置:

class DatabaseConfig:
    DEFAULT_HOST = "localhost"
    DEFAULT_PORT = 5432
    DEFAULT_CONNECT_TIMEOUT = 60
    DEFAULT_CLIENT_ENCODING = "utf-8"
    DEFAULT_SSLMODE = "disable"

    def __init__(self, dbconf):
        self.logger = setup_logger()
        _dbconf = dict(dbconf)

        # checking for database type
        dbtype = _dbconf.get('db')
        if dbtype != 'sqlite' and dbtype != 'postgres':
            msg = f"Invalid value {dbtype} of parameter 'db'. Should be 'sqlite' or 'postgres'"
            self.logger.error(msg)
            raise Exception(msg)
        else:
            self.db_type = dbtype

        dbopt = _dbconf.get('dbopt')
        if dbopt is None:
            msg = f"Invalid value {dbopt} of parameter 'dbopt'."
            self.logger.error(msg)
            raise Exception(msg)

我的测试用例:

import unittest
from analyzer.configmanager import DatabaseConfig
from analyzer.analyzerlogging import setup_logger

# Invalid dbopt (for sqlite)

class TestDatabaseConfigInit(unittest.TestCase):
  def test_UT_DATABASE_CONFIG_INIT_006(self):
      try:
          DatabaseConfig({'db' : 'sqlite', 'dbopt' : 'abc'})
      except Exception as e:
          expectedOutput = "Invalid value abc of parameter 'dbopt'."
          self.assertEqual(str(e), expectedOutput)

 if __name__ == "__main__":
    unittest.main()

错误:

test_UT_DATABASE_CONFIG_INIT_006 (ut.test_database_config_init.TestDatabaseConfigInit) ... FAIL
NoneType: None

======================================================================
FAIL: test_UT_DATABASE_CONFIG_INIT_006 (ut.test_database_config_init.TestDatabaseConfigInit)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "d:\Python\yieldnews\ut\test_database_config_init.py", line 60, in test_UT_DATABASE_CONFIG_INIT_006
    DatabaseConfig({'db' : 'sqlite', 'dbopt' : 'abc'})
AttributeError: 'str' object has no attribute 'get'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "d:\Python\yieldnews\ut\test_database_config_init.py", line 63, in test_UT_DATABASE_CONFIG_INIT_006
    self.assertEqual(str(e), expectedOutput)
AssertionError: "'str' object has no attribute 'get'" != "Invalid value abc of parameter 'dbopt'."
- 'str' object has no attribute 'get'
+ Invalid value abc of parameter 'dbopt'.


----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (failures=1)

标签: pythonpython-unittest

解决方案


推荐阅读