简体   繁体   中英

How to unit test this lambda code?

Say, I have something like the following Python code:

try:
    from fabulous.color import fg256
    format_info = lambda x: fg256(63, unicode(x, 'utf-8')).as_utf8
except ImportError:
    format_info = lambda x: '\033[1;30m' + x + '\033[0m'

How can I unit test this?

Is it worth testing?

There is a need to mock the import statement so that both branches are excised. This is fairly trivial -- for example, mock fg256 to have a side effect of raise ImportError .

Matching that the returned string has the right control characters is fine but feels brittle.

What exactly is it that you want to test? You seem to have two unrelated cases here;

  • importing fails
  • lambda returns correct info

It's not really your responsibility to check that not using your code fails; but if you want to test this nevertheless (perhaps because this is code somebody has posted on a popular forum) I would separate it into two distinct tests.

We don't know what your lambda is supposed to return, but by the looks of it, it should return a string similar to what you assign in the except branch?

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