2

I'm using a filter to remove empty values from a list:

def clean_list(inp):
  return filter(None, inp)

How do I unit-test this piece of code?

All of the following fail because the return of clean_list is a filter object and it doesn't match any of these:

assert clean_list(['']) == []
assert clean_list(['']) == ['']
assert clean_list(['']) == filter(None, [''])
assert clean_list(['']) == filter(None, [])
Community
  • 1
  • 1
GIS-Jonathan
  • 4,347
  • 11
  • 31
  • 45
  • 2
    Consume the result into a sequence and test that? – jonrsharpe Jul 28 '16 at 20:47
  • 1
    **assert list(clean_list['']) == []** – mtadd Jul 28 '16 at 20:51
  • @mtadd - jon's comment lead me to that, but I'm using parameterization - Is this possible within a parameterized context? – GIS-Jonathan Jul 28 '16 at 20:52
  • This specific example is simple enough that it doesn't need to be unit tested. It's just a convenience function that removes the need to call `filter` with `None` as the first argument. `filter` is already well documented and tested. – Dunes Jul 28 '16 at 21:32
  • @Dunes - That's a good point, but my actual code is more complex than the example above - it's integrated in a function that can have multiple return types, one of which is this filter. So I do need to be able to do a test. – GIS-Jonathan Aug 17 '16 at 15:00
  • @GIS-Jonathan It's hard to be sure without an actual example. But it sounds like you should be testing this other function with the multiple return types. That is, given these inputs, did it return the filter? To do that you would mock `clean_list` and check that you got the mock's return value. – Dunes Aug 17 '16 at 15:06

1 Answers1

2

Based on the comments and confirmation from this question, it seems the best solution is to "consume" the filter. Because I'm using parameterized testing, the best option is to do this in the function itself and return a plain list.

So my clean_list function is now:

def clean_list(inp):
  return list(filter(None, inp))

and the following unit test now passes:

assert clean_list(['']) == []
Community
  • 1
  • 1
GIS-Jonathan
  • 4,347
  • 11
  • 31
  • 45