AssertionError:“'str'对象没有属性'get'”

2024-10-05 10:45:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手。我有一个class DatabaseConfig包含一些数据库配置信息。我使用Unittest为它编写了一个测试用例,脚本是如果dbopt无效(比如'dbopt' : 'abc'),那么预期的输出是抛出异常: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)


Tags: oftestselfdefaultgetparameterinitvalue

热门问题