简体   繁体   中英

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

im not understanding why I'm getting this errors because when I pass 'height' as -1, it must change 'error' to 'Height must be .GE to zero' and that tests case passed.

However when I test base case 0. It says there is nothing in the list? can someone explain why? or tell me what's wrong with my code

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

TEST CASE: 100_101 failed and 100_120 passed

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'])

Error Generation because of failed test: self.assertEquals('0', dict['height']) TypeError: 'NoneType' object has no attribute ' getitem '

If the height key exists, and height >= 0 , nothing will be returned. That means dict will be None , and you'll get the error you're getting. You just need to ensure that a usable value is returned in all instances.

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

It doesn't even seem necessary to return values though. All you're doing is mutating the parameter. You could just use the mutated parameter.

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'])

And as noted in the comments, naming a variable the same name as a built-in is a bad idea. I renamed dict to data so you aren't shadowing the built-in dict function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM