I have an Sport class defined as:
Sport:
- name
- other fields
I have a test where I want to verify that adding the sport 'rugby' is contained in the list of sport_objects.
Currently, the test is brittle, checking the name of the object at the index I know it's at:
self.assertEquals('rugby', sports_objects[3].name)
I'd like to change this to self.assertIn() so the test isn't as brittle and won't be affected if the index changes (since I don't care about the order here).
Is there a way to change this (using a lambda function?) without relying on the index?
Edit:
Both answers given work great. I have multiple assert statements, so my final solution is:
sports_names = [i.name for i in sports_objects]
self.assertIn('rugby', sports_names)
self.assertIn('baseball', sports_names)
2 Answers 2
self.assertIn('rugby', [sport_object.name for sport_object in sports_objects])
Comments
You can always do:
self.assertIn('rugby', (x.name for x in sports_objects))
or something like
import operator
op = operator.attrgetter("name")
self.assertIn('rugby', map(op, sport_objects))