I am checking data output in some testing code, and only some fields can be None, but I think this can be better:
for key in data[0].keys():
self.assertIn(key, data_model)
if data[0][key] is None:
self.assertTrue('rate' in key or 'percentage' in key or 'ratio' in key)
continue
self.assertIsInstance(data[0][key], data_model[key])
Mostly I don't like the ... or ... in the assertTrue
1 Answer 1
A few things:
your indentation looks weird
you could store
data[0]
in some variable with a relevant name.you could iterate over both keys and values with
iteritems()
/items()
you do not need
continue
here. A simpleelse
would do the trick and is more explicit.The line you don't quite like could be replaced by something like :
self.assertTrue(any(w in key for w in ('rate', 'percentage', 'ratio')))
The resulting code would be :
first_data = data[0]
for key, val in first_data.items():
self.assertIn(key, data_model)
if val is None:
self.assertTrue(any(w in key for w in ('rate', 'percentage', 'ratio')))
else:
self.assertIsInstance(val, data_model[key])
-
\$\begingroup\$ Thanks - any was exactly what I wanted, just hadn't thought of it. Also good suggestion about items(), and I agree about the else \$\endgroup\$user3610360– user36103602016年06月30日 14:35:08 +00:00Commented Jun 30, 2016 at 14:35