Skip to content

Commit 8a58b85

Browse files
asavoyjkeyes
authored andcommitted
Fix TypeError when incrementing a None value (intercom#162)
* Fix TypeError when incrementing a None value Code like this: ```python intercom_user.increment('logins') ``` Can throw a `TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'` if logins has a `None` value. As the increment code already assumes that a missing key should be treated as zero, I don't think it's that much of a stretch to extend this to `None` values. * Add test coverage.
1 parent abcc272 commit 8a58b85

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

intercom/traits/incrementable_attributes.py

+2
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,6 @@ class IncrementableAttributes(object):
55

66
def increment(self, key, value=1):
77
existing_value = self.custom_attributes.get(key, 0)
8+
if existing_value is None:
9+
existing_value = 0
810
self.custom_attributes[key] = existing_value + value

tests/integration/test_user.py

+4
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ def test_increment(self):
5757
user.increment('karma')
5858
intercom.users.save(user)
5959
self.assertEqual(user.custom_attributes["karma"], karma + 2)
60+
user.custom_attributes['logins'] = None
61+
user.increment('logins')
62+
intercom.users.save(user)
63+
self.assertEqual(user.custom_attributes['logins'], 1)
6064

6165
def test_iterate(self):
6266
# Iterate over all users

tests/unit/test_user.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -405,7 +405,8 @@ def setUp(self): # noqa
405405
'mad': 123,
406406
'another': 432,
407407
'other': time.mktime(created_at.timetuple()),
408-
'thing': 'yay'
408+
'thing': 'yay',
409+
'logins': None,
409410
}
410411
}
411412
self.user = User(**params)
@@ -430,6 +431,11 @@ def it_can_increment_new_custom_data_fields(self):
430431
self.user.increment('new_field', 3)
431432
eq_(self.user.to_dict()['custom_attributes']['new_field'], 3)
432433

434+
@istest
435+
def it_can_increment_none_values(self):
436+
self.user.increment('logins')
437+
eq_(self.user.to_dict()['custom_attributes']['logins'], 1)
438+
433439
@istest
434440
def it_can_call_increment_on_the_same_key_twice_and_increment_by_2(self): # noqa
435441
self.user.increment('mad')

0 commit comments

Comments
 (0)