jamielennox / requests-mock

Mocked responses for the requests library
https://requests-mock.readthedocs.io
Apache License 2.0
450 stars 71 forks source link

Make NoMockAddress inherit from BaseException #234

Open joaoe opened 1 year ago

joaoe commented 1 year ago

Hi. In my project, the main app code issues some http requests. Some of these requests are allowed to fail with a default empty response, including failing due to http error, response content parsing, schema validation, etc... So we have a try/except around the session.get() call which traps everything and logs the error for those optional request and then proceeds to return an empty default object.

The problem is that this except also catches NoMockAddress.

Thinking about it more holistically, NoMockAddress should not be caught at all by try/excepts in the application code being tested.

If you see for instance pytest, pytest defined an exception type called Outcome which inherits from BaseException. That Outcome exception is what they use as Base for a Failed test or Skipped test, so to ensure (somewhat) that the code being tested is not trapping pytest's own internal exceptions.

NoMockAddress should have the same behavior. Now, one way to fix this would be to just make MockException inherit from BaseException but I don't know how triggered some purists or static code checkers would be. There could also be someone arguing to keep the old (albeit less useful) behavior.

So, perhaps add a force=True parameter or something with a better name to requests_mock.get which would use a new type of NoMockAddress exception which inherits from BaseException ?

jamielennox commented 1 year ago

I'll have a think on this one, but for the sake of argument I'd say the correct thing here would be for your code to catch RequestsException or HttpError depending on what you think you'll catch?

https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/

joaoe commented 1 year ago

That section of the library is a bit more holistic and call other functions to parse output, like json, pandas stuff, perhaps xml and so on.