Skip to content

Instantly share code, notes, and snippets.

@zoka123
Last active February 8, 2020 15:37
Show Gist options
  • Save zoka123/637cc7f33e53d1335ce6daac0807a6e8 to your computer and use it in GitHub Desktop.
Save zoka123/637cc7f33e53d1335ce6daac0807a6e8 to your computer and use it in GitHub Desktop.
Issue with SF WebTestCase and similar API tests based on the simulated requests

Let's say we want to test that after we successfuly send POST request, we can GET the same data on another endpoint. Pretty common for a CRUD-like apps.

Let's further assume our entity after creation from the POST request payload will result with a primary entity (e.g. Book) and child entities (2 Authors). We're using the constructor to create the entity (no setters) and connect everything:

$tags = .. // result is Tag[]

$book = new Book($title, $something, $tags);
...
$em->persist($book);
$em->flush();

If there is an issue with the Entity relationships configuration (e.g. missing cascade: persist) the EM flush call will be successful (no exceptions) but only the primary entity will be actually flushed to the database, and the children will not as they are not managed entities.

If we're using simulated requests, they are based on a stateful instance of your app, meaning the same Kernel and the same EM object instance will be used for both operation. Since the EM caches the objects, calling find after flushing the entitiy will return the children attached, since it will not perform a DB lookup.

In the reality, first request will create only the parent, and calling find on a fresh EM instance will lookup the DB to hydrate the entity, and because of the bug with the entity configuration, children will not be there.

API test based on real HTTP requests will immediately discover this, while tests running with simulated requests will not.

Conclusion

There is a bug with entities configuration that will go under the radar with simulated requests and will cause tests with real HTTP requests to fail immediately due to the unintended behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment