Python: raise Exception if file with name “foobar” gets opened

  • A+

I have a huge code base before me, and I have a place where a file with name "foobar" gets written.

I have no clue where this file gets read.

My idea how to solve this:

  1. do monkey patching or mocking. An exceptions should get raised if a file with this name gets opened.
  2. run all tests and see where the exception gets raised.

How to let the interpreter raise an exception if a file with given name gets opened?

I am sure that the place I search is pure python, not a c-extension.

I use Python 2.7

You can override (shadow) builtin open function. Add this in your main module:

import __builtin__  open_file =  def fake_open(filename, *args, **kwargs):     if filename == 'foobar':         raise Exception('foobar filename')     else:         return open_file(filename, *args, **kwargs) = fake_open 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: