Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: raise Exception if file with name "foobar" gets opened

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

like image 977
guettli Avatar asked Apr 27 '18 10:04

guettli


1 Answers

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

import __builtin__

open_file = __builtin__.open

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

__builtin__.open = fake_open
like image 192
ndpu Avatar answered Sep 19 '22 23:09

ndpu