0

When writing unit tests, I can use unittest.mock to isolate dependencies and monitor use of the mocked functions. Can I do the same with calls to builtin functions?

In particular, it would be nice to mock open() so that I can provide test input, or monitor output, without involving disk files. Is this possible, and adviseable? (I already know this can be done, without mocking, for functions that accept an open file object rather than a filename.)

alexis
  • 48,685
  • 16
  • 101
  • 161
  • You can define your own `open`, your own `print`, whatever... You can have a string called `open`, a `unittest.mock` called `open`. These would shadow the builtin. – ForceBru Oct 29 '17 at 16:10
  • Thanks for the tip, @Wyatt! I'll see if the solution works with `unittest.mock`, and if it does I'll close my question. – alexis Oct 29 '17 at 16:51
  • 1
    Indeed it works... the [answer by Michele d'Amico](https://stackoverflow.com/a/34677735/699305) (the second answer), not the accepted one. – alexis Oct 29 '17 at 18:04

0 Answers0