Skip to content

Instantly share code, notes, and snippets.

@gcphost
Last active March 26, 2016 21:35
Show Gist options
  • Save gcphost/8d82e37efb712edc4c88 to your computer and use it in GitHub Desktop.
Save gcphost/8d82e37efb712edc4c88 to your computer and use it in GitHub Desktop.
Laravel 5 PHPUnit SeeOrSaveJsonStructure Trait to automatically save json results then validate them.

Validate Laravel 5 JSON responses with SeeOrSaveJsonStructure and PHPUnit

I've been building a Laravel based json api for fun and one major part of it is testing the results of the API. Once I know my results are good I want to use them to validate future tests. I had setup a couple local variables, copied and pasted my results and built the functions to remap the arrays for validation but this was a pain. So this gist will give you a trait to automatically save json responses and validate them from the file.

Follow me on on twitter or asked.io.

Install

class TestCase extends Illuminate\Foundation\Testing\TestCase
{
  use SeeOrSaveJsonStructure;
  
  ...
  • Edit your phpunit.xml file
  • In the php tag add the new env variables.
  • Define your RESPONSE_FOLDER
<php>
   <env name="SAVE_RESPONSES" value="true"/>
   <env name="RESPONSE_FOLDER" value="C:\jsonapi"/>
</php>

Usage

Call $this->seeOrSaveJsonStructure() after you've called $this->json().

    public function testSort()
    {
        $this->json('GET', '/api/user?sort=-id');
        $this->seeOrSaveJsonStructure();
    }

When SAVE_RESPONSES is enabled the response from your json call will be saved to your RESPONSE_FOLDER in an easy to find .json file.

When SAVE_RESPONSES is disabled your json file will be used to validate the json structure with seeJsonStructure().

The MIT License (MIT)
Copyright (c) 2016 William Bowman (gcphost@gmail.com, asked.io)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<?php
trait SeeOrSaveJsonStructure
{
/**
* See a json result from a file or save json result to file.
*
*/
public function seeOrSaveJsonStructure()
{
if (!env('RESPONSE_FOLDER')) {
return $this;
}
$this->setup();
$file = rtrim(env('RESPONSE_FOLDER'), '\\/').DIRECTORY_SEPARATOR.class_basename(debug_backtrace()[1]['class']).'-'.debug_backtrace()[1]['function'].'.json';
if (!env('SAVE_RESPONSES', false) && file_exists($file)) {
$this->seeJsonStructure(json_decode(file_get_contents($file), true));
return $this;
}
file_put_contents($file, json_encode($this->getKeys($this->response->getContent())));
return $this;
}
/**
* Create the response folder.
*
* @return void
*/
private function setup()
{
if (!is_dir(env('RESPONSE_FOLDER'))) {
mkdir(env('RESPONSE_FOLDER'), 0600, true);
}
}
/**
* Return a array of keys.
*
* @param array $array
*
* @return array
*/
private function arrayKeys($array)
{
$results = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$results = array_merge($results, [$key => array_merge(array_keys($value), $this->arrayKeys($value))]);
}
}
return $results;
}
/**
* Get keys from a json array.
*
* @param string $content
*
* @return arrayKeys
*/
private function getKeys($content)
{
return $this->arrayKeys(json_decode($content, true));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment