2017 © Pedro Peláez
 

library json_matcher

Collection if JSON matchers for painless usage

image

fesor/json_matcher

Collection if JSON matchers for painless usage

  • Tuesday, May 30, 2017
  • by fesor
  • Repository
  • 2 Watchers
  • 18 Stars
  • 29,465 Installations
  • PHP
  • 3 Dependents
  • 0 Suggesters
  • 0 Forks
  • 4 Open issues
  • 12 Versions
  • 9 % Grown

The README.md

Json Matcher

Build Status Latest Stable Version Latest Unstable Version License Scrutinizer Code Quality Total Downloads, (*1)

Assertion library for simplifying JSON data and structure verification in your tests. It's framework-agnostic, so you can use it with PhpUnit, PhpSpec, Peridot or whatever framework you use., (*2)

Why another JSON assertion library?

If you tried to test your JSON based REST APIs, then you probably faced a several issues:, (*3)

  • You can't simply check is a response is equal to given string as there are things like server-generated IDs and timestamps.
  • Key ordering should be the same both for your API and for expected JSON.
  • Matching the whole responses breaks DRY for the tests

All these issues can be solved with two simple things: JSON normalization and key exclusion on matching. This is what this library does. It provides you a way to verify data in given JSON in multiple steps instead of one big assertion., (*4)

For example we are developing an friend list feature for our API for. What we want to check is only is given user presents in response, we don't want to check whole response, it could be done via json schema validation or on another test cases., (*5)


$alice = new User('Alice', 'Miller'); $john = new User('John', 'Smith'); $alice->addFriend($john); $json = JsonMatcher::create( json_encode($alice->toArrayIncludingFriends()), ['id', 'created_at'] );

In above example we just created an JsonMatcher instance and specified excluded-by-default keys (id and created_at). Excluded keys will be removed from JSON and it's values will not interfere in equality assertion. You can also override this list of keys via matching excluding and including options., (*6)

Then we can check is John presents in Alice's friend list at some specific position via json paths:, (*7)

$json->equal(json_encode($john->toArray()), ['at' => 'friends/0']);

Or if we don't know specific position, we can just check is John just presents in our friendlist., (*8)

$json->includes(json_encode($john->toArray()), ['at' => 'friends']);

Or we can just verify is any John presents in Alice's friend list:, (*9)

$json->includes('{"first_name": "John"}'), ['at' => 'friends']);

Getting started

You can install this library via composer:, (*10)

composer require fesor/json_matcher

Then you will need an JsonMatcher instance to be created. To do this, you can:, (*11)

  • manually create instance with all dependencies and set subject
  • use named constructor JsonMatcher::create as static factory-method. It will handle all dependencies for you.
  • use JsonMatcherFactory. This is useful when you have some IoC container in your test framework (Behat for example). In this case you'll need to register this class as a service.

Subject on which assertion will be preformed is setted up in matcher consturctor. If you want to reuse the same instance of matcher for every assertions, you can just change subject via setSubject method., (*12)

Example:, (*13)

$jsonResponse = JsonMatcher::create($response->getContent());

// or you can use factory instead
$jsonResponse = $matcherFactory->create($response->getContent());

// and there you go, for example you may use something like this 
// for your gherkin steps implementations
$jsonResponse
    ->hasSize(1, ['at' => 'friends']) // checks that list of friends was incremented
    ->includes($friend, ['at' => 'friends']) // checks that correct record contained in collection
;

You can provide list of excluded-by-default keys as second argument in constructors:, (*14)

$matcher = JsonMatcher::create($subject, ['id', 'created_at']);

Please note, that id key will be ignored by default., (*15)

Matchers

All matchers are supports fluent interface, negative matching and some options. See detailed description for more information about what options each matcher has., (*16)

equal

This is most commonly used matcher. You take two json strings and compare them. Except that before compassion this matcher will normalize structure of both JSON strings, reorder keys, exclude some of them (this is configurable) and then will simply assert that both strings are equal. You can specify list of excluded keys with excluding options:, (*17)

$actualJson = '["id": 1, "json": "spec"]';
$expectedJson = '["json": "spec"]';
$matcher
    ->setSubject($actualJson)
    ->equal($expectedJson, ['excluding' => ['id']])
;

If you have some keys, which contains some time dependent value of some server-generated IDs it is more convenient to specify list of excluded-by-default keys when you construct matcher object:, (*18)

$matcher = JsonMatcher::create($subject, ['id', 'created_at', 'updated_at']);

If you want the values for these keys to be taken into account during the matching, you can specify list of included keys with including options, (*19)

$matcher = JsonMatcher::create($response->getContent(), ['id', 'created_at', 'updated_at']);
$jsonResponseSubject->equal($expectedJson, ['including' => ['id']]);

Also you can specify json path on which matching should be done via at options. We will back to this later since all matchers supports this option., (*20)

includes

This matcher works a little different from equal matcher. What it does is recursively scan subject JSON and tries to find any inclusions of JSON subset. This is useful for cases when you checking that some record exists in collection and you do not know or don't want to know specific path to it., (*21)

$json = <<<JSON
{
    "id": 1,
    "name": "Foo",
    "collection": [
        {"id": 1, "name": "Foo"},
        {"id": 2, "name": "Bar"},
    ]
}
JSON;

$matcher
    ->setSubject($json)
    // check for value inclusion
    ->includes('"Foo"')
    // checks is json subset presents in any item of collection
    ->includes('{"name": "Bar"}', ['at' => 'collection'])
    // checks is json presents in collection
    ->includes('{"name": "Bar", "value": "FooBar"}', ['at' => 'collection'])
;

Since this matcher works the same way as equal matcher, it accepts same options., (*22)

hasPath

This matcher checks if given JSON have specific path ot not., (*23)

$json = <<<JSON
{
    "collection": [
        "json",
        "matcher"
    ]
}
JSON;

$matcher
    ->setSubject($json)
    ->hasPath('collection/1')
;

hasSize

This matcher checks is collection in given JSON contains specific amount of entities., (*24)

$json = <<<JSON
{
    "collection": [
        "json",
        "matcher"
    ]
}
JSON;

$matcher
    ->setSubject($json)
    ->hasSize(2, ['at' => 'collection'])
;

hasType

$json = <<<JSON
{
    "collection": [
        {},
        "json",
        42,
        13.45
    ]
}
JSON;

$matcher
    ->setSubject($json)
    ->hasType('array', ['at' => 'collection'])
    ->hasType('object', ['at' => 'collection/0'])
    ->hasType('string', ['at' => 'collection/1'])
    ->hasType('integer', ['at' => 'collection/2'])
    ->hasType('float', ['at' => 'collection/3'])
;

Negative matching

To invert expectations just call matcher methods with not prefix:, (*25)

$matcher
    ->setSubject($json)
    ->notEqual($expected)
    ->notIncludes($part)
;

Json Path

Also all methods have option, which specifies path which should be performed matching. For example:, (*26)

$actual = <<<JSON
{
    "collection": [
        "item"
    ]
}
JSON;
$expected = '"item"';
JsonMatcher::create($actual)
    ->equal($expected, ['at' => 'collection/0'])
;

Contribution

Please welcome to contribute!, (*27)

The Versions

30/05 2017

dev-1.0-dev

dev-1.0-dev

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

  • php >=7.0.1

 

The Development Requires

by Sergey Protko

30/05 2017

dev-scrutinizer-patch-1

dev-scrutinizer-patch-1

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

  • php >=7.0.1

 

The Development Requires

by Sergey Protko

08/07 2016

dev-refactoring

dev-refactoring

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

  • php >=5.6.0

 

The Development Requires

by Sergey Protko

26/05 2016

dev-json_schema

dev-json_schema

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

 

The Development Requires

by Sergey Protko

26/10 2015

dev-schema_matcher

dev-schema_matcher

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

 

The Development Requires

by Sergey Protko

22/10 2015

dev-master

9999999-dev

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

by Sergey Protko

22/10 2015

dev-0.2.x-dev

dev-0.2.x-dev

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

by Sergey Protko

22/10 2015

0.2.2

0.2.2.0

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

by Sergey Protko

22/10 2015

0.2.3

0.2.3.0

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

by Sergey Protko

05/07 2015

0.2.1

0.2.1.0

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

by Sergey Protko

11/04 2015

0.2

0.2.0.0

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

 

The Development Requires

by Sergey Protko

02/01 2015

0.1.0

0.1.0.0

Collection if JSON matchers for painless usage

  Sources   Download

MIT

The Requires

 

The Development Requires

by Sergey Protko