How to mock os.environ using py.test monkeypatch

1.8k views Asked by At

I'm trying to mock os.environ but I get this error.

       monkeypatch.setattr(os, 'environ', mock_env)
E       TypeError: unbound method setattr() must be called with monkeypatch instance as first argument (got module instance instead)

Here's my code.

 def test_feed(self):
        self.upload_file()
        def mock_env():
            return get_config()

        monkeypatch.setattr(os, 'environ', mock_env)

        response = self.app.get('/feed')

        self.assertEquals('<xml></xml>', response.data)

And here's the method I'm testing using Flask

@app.route("/feed")
def feed(env=os.environ):
    mrss_feed = FeedBurner(env=env).get_feed()
    response = make_response(mrss_feed)
    response.headers["Content-Type"] = "application/xml"

    return response
1

There are 1 answers

0
matino On

I believe you simply forgot to pass the monkeypatch fixture as argument to your test function:

def test_feed(self, monkeypatch):
    ...