Re: [Discussion] Sandbox API
| From: | Mike Schinkel | Date: | Tue, 06 Aug 2024 08:57:39 +0000 |
| Subject: | Re: [Discussion] Sandbox API | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-124797@lists.php.net to get a copy of this message | ||
> On Aug 6, 2024, at 2:09 AM, Nick Lockheart <lists@ageofdream.com> wrote:
>
> Sand Box: A first class API that allows unit testing of code with mocks
> and stubs of other classes or functions, without the need to modify the
> class under test.
>
> This is an initial idea of how a Sand Box API could work:
>
> $oSandbox = new SPLSandBox();
>
> $oSandbox->MockFunction('\mocks\fopen','\fopen');
> $oSandbox->MockFunction('\mocks\fread','\fread');
> $oSandbox->MockFunction('\mocks\fwrite','\fwrite');
> $oSandbox->MockFunction('\mocks\fclose','\fclose');
>
> $oFileManager = $oSandbox->GetInstance('MyFileManager');
>
> $oFileManager->WriteFile('/path/to/file.txt');
On the surface, this sounds like a good idea.
This is already possible to do in userland, with a few edge-cases. The edge-cases are:
1. Anything that uses
self::class or similar will break if it expects
MyFileManager to be returned instead of something like
MyFileManager_4k2x8j.
2. Anything that expects a static variable in MyFileManager to have a pre-existing
value set but an earlier use of MyFileManager will not work as expected. However,
expecting that would be against testing best practices so I don't see this as a real concern
given your use-case.
OTOH, a userland implementation will also not be very performant when compared to a potential PHP
core implementation, making it less than ideal for testing.
However, doing a userland implementation would be a good proof-of-concept, allow others to try it,
allow others to contribute to the exact syntax and semantics, and finally a userland implementation
could reveal any potential hidden issues in the design before moving on to a proper implementation
in C for PHP core.
-Mike
P.S. If you are unfamiliar with how to implement in userland you can use the same techniques I used
in my proof-of-concept for Userland Packages: https://github.com/mikeschinkel/userland-packages.
If that link is not enough and you instead want to ask specific questions about how to implement in
PHP, feel free to contact me off-list.