python - PYTHON : TypeError: 'NoneType' object has no attribute '__getitem__' for TESTCASE

标签 python error-handling testcase

我不明白为什么会收到此错误,因为当我将“height”传递为-1时,必须将“error”更改为“Height must be .GE to zero”
测试用例通过了。

但是,当我测试基本案例0时,它说列表中没有内容?有人可以解释为什么吗?或告诉我我的代码有什么问题

def adjust(values):
      #default
      height = 0

      if ('height' in values):
          try:
          height = float(values['height'])
      except ValueError:
          values['error'] = 'non-numeric height'
          return values

      if height < 0:
          values['error'] = 'Heights needs to be .GE 0'
          return values

测试案例:100_101失败并且100_120通过
def test100_010HeightLowBound(self):
    dict = nav.adjust({'op': 'adjust', 'observation': '3d.13','height': '0'})
    self.assertEquals('0', dict['height'])

def test100_020OutofBound(self):
    dict = nav.adjust({'op': 'adjust', 'observation': '3d1.3', 'height': '-1'})
    self.assertEquals('Heights needs to be .GE 0', dict['error'])

由于测试失败而产生错误:
self.assertEquals('0',dict ['height'])
TypeError:“NoneType”对象没有属性“ getitem

最佳答案

如果存在height键和height >= 0,则不会返回任何内容。这意味着dict将是None,并且您会得到错误。您只需要确保在所有实例中都返回一个可用的值。

def adjust(values):
      height = 0

      if ('height' in values):
          try:
             height = float(values['height'])

          except ValueError:
              values['error'] = 'non-numeric height'
              return values

      if height < 0:
          values['error'] = 'Heights needs to be .GE 0'

      return values # Return values regardless of the previous checks

似乎甚至没有必要返回values。您要做的就是更改参数。您可以只使用mutated参数。
def adjust2(values):
      height = 0

      if ('height' in values):
          try:
              height = float(values['height'])

          except ValueError:
              values['error'] = 'non-numeric height'
              return

      if height < 0:
          values['error'] = 'Heights needs to be .GE 0'

def test100_010HeightLowBound(self):
    data = {'op': 'adjust', 'observation': '3d.13','height': '0'}
    nav.adjust(data)
    self.assertEquals('0', data['height'])

并且如注释中所述,给变量命名与内置变量相同的名称是一个坏主意。我将dict重命名为data,因此您不会隐藏内置的dict函数。

关于python - PYTHON : TypeError: 'NoneType' object has no attribute '__getitem__' for TESTCASE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54815514/

相关文章:

php更改 fatal error 格式

java - 如何解决 OptimisticLockingFailureException?

python - 强制转换为 Unicode : need string or buffer, 找到标记

python - PyQT5 QComboBox - 获取组合框的值

python - 强制使用 virtualenv pip

java - 运行 JUNIT 测试用例时出错

python 在一个测试函数中测试代码覆盖率和多个断言

python - 使用 for 循环和 if 语句求根迭代

android - 下载Google Play服务

c++ - 捕获不使用 try/catch 抛出的异常