add context to fixtures
PR for our telegram conversation.
This allows us to have context on fixture files. If you have a general/dynamic connector mock for your tests you will end up with a bunch of fixtures you have no idea where they belong to. It is even worse when you use some payload hashing as below.
AvalaraConnector::class => function (PendingRequest $request): Fixture {
$name = implode('/', [
parse_url($request->getUrl(), PHP_URL_HOST),
parse_url($request->getUrl(), PHP_URL_PATH),
Str::upper($request->getMethod()->value),
hash('md5', json_encode(Arr::sortRecursive(array_merge(
$request->query()->all(),
$request->body()?->all() ?? [],
)), JSON_THROW_ON_ERROR)),
]);
return MockResponse::fixture($name);
},
As you can see each different request will end up with a corresponding fixture - but you won't be able to tell from a fixture where it belongs to, if it's still needed or anything.
That's where fixture context comes in handy - you can add whatever context you want that will be persisted in your fixture files - for example the plain payload or the name of the test it was used in or anything else.
You can do so by chaining withContext() on your fixture instance.
usage examples
// simple single key setter
return MockResponse::fixture($name)->setContext('query', $request->query()->all());
// simple withContext chain
return MockResponse::fixture($name)->withContext(['query' => $request->query()->all()]);
// complex context manipulation
$fixture = MockResponse::fixture($name);
$fixture->getContext()->when($condition, fn(ArrayStore $context) => $context->add('key', 'value'));
return $fixture;
You have access to the underlying ArrayStore via getContext() and can use all the methods available there to manipulate or interact with the context. For sure you can also use getContext() to retrieve a specific context value.
The context isn't used anywhere in Saloon itself - it's only made available and persisted so that you can check it manually or do some checks in your own code with it. So everything you do with it is up to you - only restriction: it has to be JSONable.
I haven'T tested for compatibility with https://github.com/saloonphp/saloon/pull/425 but there shouldn't be any real conflicts.
Hey @Gummibeer - thanks for this PR, and sorry for the delay, life has been really busy. I will have a look through this and hopefully soon we can merge it in.
@Gummibeer Seems like something is up with the tests 🤔 Obviously no rush but if you get a spare 5 minutes it'll be good if you could take a look please? (Btw I have merged the latest of v3 into your branch)