by simonw · 5y ago · 0 comments
> pytest also goes further and inspects the arguments to functions to figure out more things.
I think this pattern deserves its own category. I think of it as the Python world's variation on "dependency injection" and I really like it.
In pytest you can use argument names to request that specific test fixtures be made available to your test function: https://docs.pytest.org/en/6.2.x/fixture.html
I use it in Datasette to allow plugins to define their own view functions, which will be passed the specific objects that they declare a need for in order to process an incoming HTTP request: https://docs.datasette.io/en/stable/plugin_hooks.html#regist...
But if you have to work in a new project / code base and there is a lot of this kind of magic, then it's really really hard to figure out how things work and where you need or even can make changes to change behaviour.
I would go so far to say that this is actually an anti-pattern.
The alternative that I prefer: have a sane default that is generated somewhere and searchable for anyone who doesn't know the convention yet. And in the case of pytest, I think this is just a shortcoming of the language in spite of a better way of doing proper dependency-injection. I remember very well that angular 1.x did something very similar and it was very confusing (they called .toString on the function to find the argument-names). It also violates the general idea of being able to safely refactor a method argument name without breaking things.
I don’t know if there is a term for this concept. I’ve always seen it as some form of Dependency Injection/IoC but at the method level instead of object creation.
IIRC the Actix web framework in Rust does something similar for handler functions.
Test functions are never called explicitly and would otherwise (like unittest TestCase methods) never have any arguments, so in this context maybe it's clear that any arguments they do have must be magical.
The decorator pattern seems to fit, from my POV. The framework takes your code, creates a proxy that implements the interface, and then wraps your method in a method that does the stuff you asked for with the annotations before and after your method gets called.