APISchema

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

1.34 2017-11-30T16:29:26Z
  - Define prototype of type before calling it

1.33 2017-11-30T14:39:09Z
  - Resolve anyOf, allOf and oneOf keywords when serving Mock Server and API Document

1.32 2017-11-30T06:08:51Z
  - MockServer always returns bytes

1.31 2017-11-29T02:30:47Z
  - MockServer support `response => {body => 'bmi', encoding => 'json'}` syntax

1.30 2017-11-20T17:00:38Z
   - Empty input could pass validations unexpectedly
   - Add . to lib

1.29 2017-11-20T01:34:11Z
   - Handle boolean on generating document(1.28 was broken)

1.28 2017-11-17T09:49:53Z
   - Handle boolean on generating document

Changes  view on Meta::CPAN

   - Inject routes to an existing router object

1.22 2016-04-20T06:08:32Z
   - Update Valiemon

1.21 2015-11-24T02:35:14Z
    - Added missing prereqs as reported by CPANTS

1.2 2015-11-20T04:37:28Z

    - X-Error-Cause header indicates whether the response comes from app or validator

1.1 2015-11-19T06:32:07Z
    - Add method and path info to documentation TOC (Sixeight++)

1.04 2015-10-15T10:38:54Z
    - mock server feature

1.03 2015-10-06T07:25:49Z
    - Determine the status code from the detail of failure (aereal++)

LICENSE  view on Meta::CPAN

software and to any other program whose authors commit to using it.
You can use it for your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Specifically, the General Public License is designed to make
sure that you have the freedom to give away or sell copies of free
software, that you receive source code or can get it if you want it,
that you can change the software or use pieces of it in new free
programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of a such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must tell them their rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

LICENSE  view on Meta::CPAN


                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License Agreement applies to any program or other work which
contains a notice placed by the copyright holder saying it may be
distributed under the terms of this General Public License.  The
"Program", below, refers to any such program or work, and a "work based
on the Program" means either the Program or any work containing the
Program or a portion of it, either verbatim or with modifications.  Each
licensee is addressed as "you".

  1. You may copy and distribute verbatim copies of the Program's source
code as you receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice and
disclaimer of warranty; keep intact all the notices that refer to this
General Public License and to the absence of any warranty; and give any
other recipients of the Program a copy of this General Public License
along with the Program.  You may charge a fee for the physical act of
transferring a copy.

LICENSE  view on Meta::CPAN

    exchange for a fee.

Mere aggregation of another independent work with the Program (or its
derivative) on a volume of a storage or distribution medium does not bring
the other work under the scope of these terms.

  3. You may copy and distribute the Program (or a portion or derivative of
it, under Paragraph 2) in object code or executable form under the terms of
Paragraphs 1 and 2 above provided that you also do one of the following:

    a) accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of
    Paragraphs 1 and 2 above; or,

    b) accompany it with a written offer, valid for at least three
    years, to give any third party free (except for a nominal charge
    for the cost of distribution) a complete machine-readable copy of the
    corresponding source code, to be distributed under the terms of
    Paragraphs 1 and 2 above; or,

    c) accompany it with the information you received as to where the
    corresponding source code may be obtained.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form alone.)

Source code for a work means the preferred form of the work for making
modifications to it.  For an executable file, complete source code means
all the source code for all modules it contains; but, as a special
exception, it need not include source code for modules which are standard
libraries that accompany the operating system on which the executable
file runs, or for standard header files or definitions files that
accompany that operating system.

  4. You may not copy, modify, sublicense, distribute or transfer the
Program except as expressly provided under this General Public License.
Any attempt otherwise to copy, modify, sublicense, distribute or transfer
the Program is void, and will automatically terminate your rights to use
the Program under this License.  However, parties who have received
copies, or rights to use copies, from you under this General Public
License will not have their licenses terminated so long as such parties
remain in full compliance.

  5. By copying, distributing or modifying the Program (or any work based
on the Program) you indicate your acceptance of this license to do so,
and all its terms and conditions.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the original
licensor to copy, distribute or modify the Program subject to these
terms and conditions.  You may not impose any further restrictions on the
recipients' exercise of the rights granted herein.

  7. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of the license which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
the license, you may choose any version ever published by the Free Software
Foundation.

  8. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS

LICENSE  view on Meta::CPAN

The hypothetical commands `show w' and `show c' should show the
appropriate parts of the General Public License.  Of course, the
commands you use may be called something other than `show w' and `show
c'; they could even be mouse-clicks or menu items--whatever suits your
program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the
  program `Gnomovision' (a program to direct compilers to make passes
  at assemblers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

That's all there is to it!


--- The Artistic License 1.0 ---

This software is Copyright (c) 2014 by hitode909 <hitode909@gmail.com>.

This is free software, licensed under:

LICENSE  view on Meta::CPAN

  - "Reasonable copying fee" is whatever you can justify on the basis of media
    cost, duplication charges, time of people involved, and so on. (You will
    not be required to justify it to the Copyright Holder, but only to the
    computing community at large as a market that must bear the fee.) 
  - "Freely Available" means that no fee is charged for the item itself, though
    there may be fees involved in handling the item. It also means that
    recipients of the item may redistribute it under the same conditions they
    received it. 

1. You may make and give away verbatim copies of the source form of the
Standard Version of this Package without restriction, provided that you
duplicate all of the original copyright notices and associated disclaimers.

2. You may apply bug fixes, portability fixes and other modifications derived
from the Public Domain or from the Copyright Holder. A Package modified in such
a way shall still be considered the Standard Version.

3. You may otherwise modify your copy of this Package in any way, provided that
you insert a prominent notice in each changed file stating how and when you
changed that file, and provided that you do at least ONE of the following:

LICENSE  view on Meta::CPAN

4. You may distribute the programs of this Package in object code or executable
form, provided that you do at least ONE of the following:

  a) distribute a Standard Version of the executables and library files,
     together with instructions (in the manual page or equivalent) on where to
     get the Standard Version.

  b) accompany the distribution with the machine-readable source of the Package
     with your modifications.

  c) accompany any non-standard executables with their corresponding Standard
     Version executables, giving the non-standard executables non-standard
     names, and clearly documenting the differences in manual pages (or
     equivalent), together with instructions on where to get the Standard
     Version.

  d) make other distribution arrangements with the Copyright Holder.

5. You may charge a reasonable copying fee for any distribution of this
Package.  You may charge any fee you choose for support of this Package. You
may not charge a fee for this Package itself. However, you may distribute this

MANIFEST  view on Meta::CPAN

t/APISchema-JSON.t
t/APISchema-Resource.t
t/APISchema-Route.t
t/APISchema-Schema.t
t/APISchema-Validator.t
t/APISchema.t
t/Plack-App-APISchema-Document.t
t/Plack-App-APISchema-MockServer.t
t/Plack-Middleware-APISchema-RequestValidator.t
t/Plack-Middleware-APISchema-ResponseValidator.t
t/fixtures/author.def
t/fixtures/bmi.def
t/fixtures/boolean.def
t/fixtures/example-null.def
t/fixtures/family.def
t/fixtures/runtime-error.def
t/fixtures/status.def
t/fixtures/syntax-error.def
t/fixtures/user.def
t/test.pm
t/test/InheritedDocument.pm
t/test/fixtures.pm
META.yml
MANIFEST

META.json  view on Meta::CPAN

         "inc",
         "share",
         "eg",
         "examples",
         "author",
         "builder"
      ]
   },
   "prereqs" : {
      "configure" : {
         "requires" : {
            "Module::Build::Tiny" : "0.035"
         }
      },
      "develop" : {
         "requires" : {
            "Test::CPAN::Meta" : "0",
            "Test::MinimumVersion::Fast" : "0.04",
            "Test::PAUSE::Permissions" : "0.04",
            "Test::Pod" : "1.41",
            "Test::Spellunker" : "v0.2.7"
         }
      },
      "runtime" : {
         "requires" : {
            "Class::Accessor::Lite" : "0",
            "Class::Accessor::Lite::Lazy" : "0",
            "Class::Load" : "0",
            "HTML::Escape" : "0",
            "HTTP::Message" : "0",
            "Hash::Merge::Simple" : "0",
            "JSON::Pointer" : "0",
            "JSON::XS" : "0",
            "List::MoreUtils" : "0",
            "Path::Class" : "0",

META.json  view on Meta::CPAN

            "Text::MicroTemplate" : "0",
            "Text::MicroTemplate::DataSection" : "0",
            "Text::MicroTemplate::Extended" : "0",
            "URI::Escape" : "0",
            "URL::Encode" : "0",
            "Valiemon" : "0.04",
            "perl" : "5.014"
         }
      },
      "test" : {
         "requires" : {
            "HTTP::Request::Common" : "0",
            "Path::Class" : "0",
            "Test::Class" : "0",
            "Test::Deep" : "0",
            "Test::Deep::JSON" : "0",
            "Test::Fatal" : "0",
            "Test::More" : "0.98"
         }
      }
   },

META.json  view on Meta::CPAN

         "file" : "lib/Plack/App/APISchema/MockServer.pm"
      },
      "Plack::Middleware::APISchema::RequestValidator" : {
         "file" : "lib/Plack/Middleware/APISchema/RequestValidator.pm"
      },
      "Plack::Middleware::APISchema::ResponseValidator" : {
         "file" : "lib/Plack/Middleware/APISchema/ResponseValidator.pm"
      }
   },
   "release_status" : "stable",
   "resources" : {
      "bugtracker" : {
         "web" : "https://github.com/hitode909/APISchema/issues"
      },
      "homepage" : "https://github.com/hitode909/APISchema",
      "repository" : {
         "url" : "git://github.com/hitode909/APISchema.git",
         "web" : "https://github.com/hitode909/APISchema"
      }
   },
   "version" : "1.37",

META.yml  view on Meta::CPAN

---
abstract: 'Schema for API'
author:
  - 'hitode909 <hitode909@gmail.com>'
build_requires:
  HTTP::Request::Common: '0'
  Path::Class: '0'
  Test::Class: '0'
  Test::Deep: '0'
  Test::Deep::JSON: '0'
  Test::Fatal: '0'
  Test::More: '0.98'
configure_requires:
  Module::Build::Tiny: '0.035'
dynamic_config: 0
generated_by: 'Minilla/v3.0.14, CPAN::Meta::Converter version 2.150010'
license: perl
meta-spec:
  url: http://module-build.sourceforge.net/META-spec-v1.4.html
  version: '1.4'
name: APISchema
no_index:
  directory:

META.yml  view on Meta::CPAN

  APISchema::Validator::Result:
    file: lib/APISchema/Validator/Result.pm
  Plack::App::APISchema::Document:
    file: lib/Plack/App/APISchema/Document.pm
  Plack::App::APISchema::MockServer:
    file: lib/Plack/App/APISchema/MockServer.pm
  Plack::Middleware::APISchema::RequestValidator:
    file: lib/Plack/Middleware/APISchema/RequestValidator.pm
  Plack::Middleware::APISchema::ResponseValidator:
    file: lib/Plack/Middleware/APISchema/ResponseValidator.pm
requires:
  Class::Accessor::Lite: '0'
  Class::Accessor::Lite::Lazy: '0'
  Class::Load: '0'
  HTML::Escape: '0'
  HTTP::Message: '0'
  Hash::Merge::Simple: '0'
  JSON::Pointer: '0'
  JSON::XS: '0'
  List::MoreUtils: '0'
  Path::Class: '0'
  Plack: '0'
  Router::Simple: '0'
  Text::Markdown::Hoedown: '0'
  Text::MicroTemplate: '0'
  Text::MicroTemplate::DataSection: '0'
  Text::MicroTemplate::Extended: '0'
  URI::Escape: '0'
  URL::Encode: '0'
  Valiemon: '0.04'
  perl: '5.014'
resources:
  bugtracker: https://github.com/hitode909/APISchema/issues
  homepage: https://github.com/hitode909/APISchema
  repository: git://github.com/hitode909/APISchema.git
version: '1.37'
x_authority: cpan:HITODE
x_contributors:
  - 'Mohammad S Anwar <mohammad.anwar@yahoo.com>'
  - 'Takumi Akiyama <t.akiym@gmail.com>'
  - 'Tomohiro Nishimura <tomohiro68@gmail.com>'
  - 'aereal <aereal@aereal.org>'

README.md  view on Meta::CPAN

[![Build Status](https://travis-ci.org/hitode909/APISchema.svg?branch=master)](https://travis-ci.org/hitode909/APISchema)
# NAME

APISchema - Schema for API

# SYNOPSIS

    # bmi.def

    resource figure => {
        type => 'object',
        description => 'Figure, which includes weight and height',
        properties => {
            weight  => {
                type => 'number',
                description => 'Weight(kg)',
                example => 50,
            },
            height  => {
                type => 'number',
                description => 'Height(m)',
                example => 1.6,
            },
        },
        required => ['weight', 'height'],
    };

    resource bmi => {
        type => 'object',
        description => 'Body mass index',
        properties => {
            value  => {
                type => 'number',
                description => 'bmi value',
                example => 19.5,
            },
        },
        required => ['value'],
    };

    POST '/bmi/' => {
        title           => 'BMI API',
        description     => 'This API calculates your BMI.',
        destination     => {
            controller  => 'BMI',
            action      => 'calculate',
        },
        request         => 'figure',
        response        => 'bmi',
    };

    # main.pl

    use APISchema::DSL;
    my $schema = APISchema::DSL::process {
        include 'bmi.def';
    };

    # Routing

cpanfile  view on Meta::CPAN

requires 'perl', '5.008001';

requires 'Router::Simple';
requires 'Plack';
requires 'JSON::XS';
requires 'JSON::Pointer';
requires 'Path::Class';
requires 'Class::Load';
requires 'Class::Accessor::Lite';
requires 'Class::Accessor::Lite::Lazy';
requires 'List::MoreUtils';
requires 'Hash::Merge::Simple';
requires 'URL::Encode';
requires 'HTML::Escape';
requires 'Text::MicroTemplate';
requires 'Text::MicroTemplate::Extended';
requires 'Text::MicroTemplate::DataSection';
requires 'Text::Markdown::Hoedown';
requires 'HTTP::Message';
requires 'Valiemon', '0.04';
requires 'URI::Escape';

on 'test' => sub {
    requires 'Path::Class';
    requires 'Test::More', '0.98';
    requires 'Test::Class';
    requires 'Test::Deep';
    requires 'Test::Fatal';
    requires 'Test::Deep::JSON';
    requires 'HTTP::Request::Common';
};

eg/bmi.psgi  view on Meta::CPAN

use Plack::Request;
use APISchema::DSL;
use APISchema::Generator::Router::Simple;
use Plack::App::APISchema::Document;
use Plack::App::APISchema::MockServer;
use APISchema::Generator::Markdown;

use JSON qw(decode_json encode_json);

my $schema = APISchema::DSL::process {
    include '../t/fixtures/bmi.def';
};

my $router = do {
    my $generator = APISchema::Generator::Router::Simple->new;
    $generator->generate_router($schema);
};

my $app = sub {
    my $env = shift;

eg/bmi.psgi  view on Meta::CPAN


Start the appliction.

    carton exec -- plackup bmi.psgi

Then,

    % curl -X POST -H "Content-type: application/json" -d '{"weight": 60, "height": '1.7'}' http://localhost:5000/bmi
    {"value":20.7612456747405}

Requests and Reponses to the API are validated by Middlewares.

    % curl -X POST -H "Content-type: application/json" -d 'hello' http://localhost:5000/bmi
    {"attribute":"Valiemon::Attributes::Required","position":"/required"}

    % curl -X POST -H "Content-type: application/json" -d '{"weight": 60, "height": 'a'}' http://localhost:5000/bmi
    {"attribute":"Valiemon::Attributes::Required","position":"/required"}

    % curl -X POST -H "Content-type: application/json" -d '{"weight": 60, "height": 'a'}' http://localhost:5000/bmi
    {"attribute":"Valiemon::Attributes::Required","position":"/required"}

lib/APISchema.pm  view on Meta::CPAN

=encoding utf-8

=head1 NAME

APISchema - Schema for API

=head1 SYNOPSIS

    # bmi.def

    resource figure => {
        type => 'object',
        description => 'Figure, which includes weight and height',
        properties => {
            weight  => {
                type => 'number',
                description => 'Weight(kg)',
                example => 50,
            },
            height  => {
                type => 'number',
                description => 'Height(m)',
                example => 1.6,
            },
        },
        required => ['weight', 'height'],
    };

    resource bmi => {
        type => 'object',
        description => 'Body mass index',
        properties => {
            value  => {
                type => 'number',
                description => 'bmi value',
                example => 19.5,
            },
        },
        required => ['value'],
    };

    POST '/bmi/' => {
        title           => 'BMI API',
        description     => 'This API calculates your BMI.',
        destination     => {
            controller  => 'BMI',
            action      => 'calculate',
        },
        request         => 'figure',
        response        => 'bmi',
    };

    # main.pl

    use APISchema::DSL;
    my $schema = APISchema::DSL::process {
        include 'bmi.def';
    };

    # Routing

lib/APISchema/DSL.pm  view on Meta::CPAN

use APISchema::Schema;

# core
use Carp ();

# cpan
use Exporter 'import';
use Path::Class qw(file);

my %schema_meta = (
    ( map { $_ => "${_}_resource" } qw(request response) ),
    ( map { $_ => $_ } qw(title description destination option) ),
);

our %METHODS = (
    ( map { $_ => $_ } qw(HEAD GET POST PUT DELETE PATCH) ),
    FETCH => [qw(GET HEAD)],
);
our @DIRECTIVES = (qw(include filter resource title description), keys %METHODS);
our @EXPORT = @DIRECTIVES;

my $_directive = {};

sub process (&) {
    my $dsl = shift;

    my $schema = APISchema::Schema->new;

    local $_directive->{include} = sub {

lib/APISchema/DSL.pm  view on Meta::CPAN

        $schema->title(@_);
    };
    local $_directive->{description} = sub {
        $schema->description(@_);
    };

    my @filters;
    local $_directive->{filter} = sub {
        push @filters, $_[0];
    };
    local $_directive->{resource} = sub {
        $schema->register_resource(@_);
    };

    local @$_directive{keys %METHODS} = map {
        my $m = $_;
        sub {
            my ($path, @args) = @_;
            for my $filter (reverse @filters) {
                local $Carp::CarpLevel += 1;
                @args = $filter->(@args);
            }

lib/APISchema/DSL.pm  view on Meta::CPAN


    $dsl->();
    return $schema;
}

# dispatch directives to the definitions
sub include ($) { $_directive->{include}->(@_) }
sub title ($) { $_directive->{title}->(@_) }
sub description ($) { $_directive->{description}->(@_) }
sub filter (&) { $_directive->{filter}->(@_) }
sub resource ($@) { $_directive->{resource}->(@_) }
for my $method (keys %METHODS) {
    no strict 'refs';
    *$method = sub ($@) { goto \&{ $_directive->{$method} } };
}

# disable the global definitions
@$_directive{@DIRECTIVES} = (sub {
    Carp::croak(sprintf(
        q(%s should be called inside 'process {}' block),
        join '/', @DIRECTIVES

lib/APISchema/Generator/Markdown.pm  view on Meta::CPAN

sub new {
    my ($class) = @_;

    my $renderer = Text::MicroTemplate::DataSection->new(
        escape_func => undef
    );
    bless {
        renderer => $renderer,
        map {
            ( $_ => $renderer->build_file($_) );
        } qw(index toc route resource request response
             request_example response_example),
    }, $class;
}

sub resolve_encoding ($) {
    my ($resources) = @_;
    $resources = { body => $resources } unless ref $resources;
    my $encoding = $resources->{encoding} // { '' => 'auto' };
    $encoding = { '' => $encoding } unless ref $encoding;
    return { %$resources, encoding => $encoding };
}

sub format_schema {
    my ($self, $schema) = @_;

    my $renderer = $self->{renderer};
    my $routes = $schema->get_routes;
    my $resources = $schema->get_resources;

    my $root = $schema->get_resource_root;
    my $resolver = APISchema::Generator::Markdown::ResourceResolver->new(
        schema => $root,
    );
    return $self->{index}->(
        $renderer,
        $schema,
        $self->{toc}->(
            $renderer,
            $routes,
            $resources,
        ),
        join('', map {
            my $route = $_;
            my $req = resolve_encoding($route->request_resource);
            my $request_resource = $route->canonical_request_resource($root);

            my $codes = $route->responsible_codes;
            my $default_code = $route->default_responsible_code;
            my $response_resource = $route->canonical_response_resource($root, [
                $default_code
            ]);

            my $res = $_->response_resource;
            $res = $_->responsible_code_is_specified
                ? { map { $_ => resolve_encoding($res->{$_}) } @$codes }
                : { '' => resolve_encoding($res) };

            $self->{route}->(
                $renderer,
                $route,
                {
                    req =>  $self->{request_example}->(
                        $renderer,
                        $route,
                        APISchema::Generator::Markdown::ExampleFormatter->new(
                            resolver => $resolver,
                            spec     => $request_resource,
                        ),
                    ),
                    res => $self->{response_example}->(
                        $renderer,
                        $route,
                        $default_code,
                        APISchema::Generator::Markdown::ExampleFormatter->new(
                            resolver => $resolver,
                            spec     => $response_resource,
                        ),
                    ),
                },
                {
                    req => $self->{request}->($renderer, $route, $req),
                    res => join("\n", map {
                        $self->{response}->($renderer, $route, $_, $res->{$_});
                    } sort keys %$res),
                },
            );
        } @$routes),
        join('', map {
            my $properties = $resolver->properties($_->definition);
            $self->{resource}->($renderer, $resolver, $_, [ map { +{
                path => $_,
                definition => $properties->{$_},
            } } sort keys %$properties ]);
        } grep {
            ( $_->definition->{type} // '' ) ne 'hidden';
        } @$resources),
    );
}

1;
__DATA__
@@ index
? my ($schema, $toc_text, $routes_text, $resources_text) = @_;
# <?= $schema->title || '' ?>

?= $schema->description || ''

?= $toc_text

## <a name="routes"></a> Routes

?= $routes_text

## <a name="resources"></a> Resources

?= $resources_text

----------------------------------------------------------------
Generated by <?= __PACKAGE__ ?>

@@ toc
? my ($routes, $resources) = @_;

- [Routes](#routes)
? for (@$routes) {
    - [<?= $_->title ?>](#<?= anchor(route => $_->title) ?>) - <?= methods($_->method) ?> <?= $_->route ?>
? }
- [Resources](#resources)
? for (@$resources) {
?   next if ( $_->definition->{type} // '' ) eq 'hidden';
    - [<?= $_->title ?>](#<?= anchor(resource => $_->title) ?>)
? }

@@ route
? my ($route, $example, $text) = @_;
### <a name="<?= anchor(route => $route) ?>"></a> <?= $route->title ?>

?= $example->{req}
?= $example->{res}
?= $route->description || ''

?= $text->{req}

?= $text->{res}

@@ request_example
? my ($route, $example) = @_;
```
<?= method($route->method) ?> <?= $route->route ?><?= $example->parameter ?>
<?= $example->header_and_body ?>
```

@@ response_example
? my ($route, $code, $example) = @_;
```
HTTP/1.1 <?= http_status($code) ?>
<?= $example->header_and_body ?>
```

@@ request
? my ($route, $req) = @_;
#### Request  <?= methods($route->method) ?>
?= $req->{description} // ''

lib/APISchema/Generator/Markdown.pm  view on Meta::CPAN

?     next unless $req->{$_};
|<?= $_ ?>|<?= type($req->{$_}) ?>|-|-|
?   } # for
?   if ($req->{body}) {
?     for (sort keys %{$req->{encoding}}) {
|body|<?= type($req->{body}) ?>|<?= content_type($_) ?>|<?= content_type($req->{encoding}->{$_}) ?>|
?     } # for
?   } # $req->{body}
? } # scalar keys %$req

@@ response
? my ($route, $code, $res) = @_;
#### Response <?= http_status_code($code) ?>
?= $res->{description} // ''

? if (scalar grep { $res->{$_} } qw(header parameter body)) {
|Part|Resource|Content-Type|Encoding|
|----|--------|------------|--------|
?   for (qw(header)) {
?     next unless $res->{$_};
|<?= $_ ?>|<?= type($res->{$_}) ?>|-|-|
?   } # for
?   if ($res->{body}) {
?     for (sort keys %{$res->{encoding}}) {
|body|<?= type($res->{body}) ?>|<?= content_type($_) ?>|<?= content_type($res->{encoding}->{$_}) ?>|
?     } # for
?   } # $res->{body}
? } # scalar keys %$res

@@ resource
? my ($r, $resource, $properties) = @_;
### <a name="<?= anchor(resource => $resource) ?>"></a> `<?= $resource->title ?>` : <?= type($resource->definition) ?>
```javascript
<?= pretty_json $r->example($resource->definition) ?>
```

?= $resource->definition->{description} || ''

#### Properties

? if (scalar @$properties) {
|Property|Type|Default|Example|Restrictions|Description|
|--------|----|-------|-------|------------|-----------|
?   for my $prop (@$properties) {
?     my $def = $prop->{definition};
|`<?= $prop->{path} ?>` |<?= type($def) ?> |<?= code($def->{default}) ?> |<?= code($def->{example}, exists $def->{example}) ?> |<?= restriction($def) ?> |<?= desc($def->{description}) ?> |
?   } # $prop
? } # scalar @$properties

lib/APISchema/Generator/Markdown/ExampleFormatter.pm  view on Meta::CPAN

use strict;
use warnings;

# lib
use APISchema::Generator::Markdown::Formatter qw(json);

# cpan
use URI::Escape qw(uri_escape_utf8);
use Class::Accessor::Lite (
    new => 1,
    ro => [qw(resolver spec)],
);

sub example {
    my $self = shift;
    return $self->resolver->example(@_);
}

sub header {
    my ($self) = @_;
    my $header = $self->spec->{header} or return '';
    my $resource = $header->definition or return '';
    my $example = $self->example($resource);

    return '' unless defined $example;
    return '' unless (ref $example) eq 'HASH';
    return '' unless scalar keys %$example;

    return join "\n", map {
        sprintf '%s: %s', $_ =~ s/[_]/-/gr, $example->{$_};
    } sort keys %$example;
}

sub parameter {
    my ($self) = @_;
    my $parameter = $self->spec->{parameter} or return '';
    my $resource = $parameter->definition or return '';
    my $example = $self->example($resource);

    return '' unless defined $example;
    return '' unless (ref $example) eq 'HASH';
    return '' unless scalar keys %$example;

    return '?' . join '&', map {
        # TODO multiple values?
        sprintf '%s=%s', map { uri_escape_utf8 $_ } $_, $example->{$_};
    } sort keys %$example;
}

sub body {
    my ($self) = @_;
    my $body = $self->spec->{body} or return '';
    my $resource = $body->definition or return '';
    my $example = $self->example($resource);

    return '' unless defined $example;

    return ref $example ? json($example) : $example;
}

sub header_and_body {
    my ($self) = @_;
    join("\n", grep { defined $_ && length $_ > 0 } $self->header, $self->body);
}

lib/APISchema/Generator/Markdown/Formatter.pm  view on Meta::CPAN

package APISchema::Generator::Markdown::Formatter;
use 5.014;
use strict;
use warnings;

# core
use Exporter qw(import);
our @EXPORT = qw(type json pretty_json code restriction desc anchor method methods content_type http_status http_status_code);

# cpan
use HTTP::Status qw(status_message);
use URI::Escape qw(uri_escape_utf8);
use JSON::XS ();
my $JSON = JSON::XS->new->canonical(1);

use constant +{
    RESTRICTIONS => [qw(required max_items min_items max_length min_length maximum minimum pattern)],
    SHORT_DESCRIPTION_LENGTH => 100,

lib/APISchema/Generator/Markdown/Formatter.pm  view on Meta::CPAN

    if (ref $def) {
        for my $type (qw(oneOf anyOf allOf)) {
            if (my $union = $def->{$type}) {
                return join($bar, map { type($_) } @$union);
            }
        }
    }

    my $ref = ref $def ? $def->{'$ref'} : $def;
    if ($ref) {
        $ref = $ref =~ s!^#/resource/!!r;
        my $ref_text = "`$ref`";
        my $name = $ref =~ s!/.*$!!r;
        $ref_text = sprintf('[%s](#%s)', $ref_text, anchor(resource => $name)) if $name;
        return $ref_text;
    }

    return join $bar, map { code($_) } @{$def->{enum}} if $def->{enum};

    my $type = $def->{type};
    if ($type) {
        return sprintf '`%s`', $type unless ref $type;
        return join $bar, map { code($_) } @{$type} if ref $type eq 'ARRAY';
    }

lib/APISchema/Generator/Markdown/Formatter.pm  view on Meta::CPAN

    return $exists ? '`null`' : '' unless defined $text;
    return _code json $text;
}

sub anchor ($$) {
    my ($label, $obj) = @_;
    my $name = ref $obj ? $obj->title : $obj;
    return sprintf '%s-%s', $label, uri_escape_utf8($name);
}

sub restriction ($) {
    my $def = shift;
    return '' unless (ref $def) eq 'HASH';

    my @result = ();
    for my $r (sort @{+RESTRICTIONS}) {
        next unless defined $def->{$r};

        if (ref $def->{$r}) {
            push @result, _code sprintf "$r%s", json $def->{$r};
        } else {
            push @result, _code sprintf "$r(%s)", json $def->{$r};
        }
    }
    return join ' ', @result;
}

sub desc ($) {
    my $text = shift || '';
    $text = $text =~ s/[\r\n].*\z//sr;
    $text = substr($text, 0, SHORT_DESCRIPTION_LENGTH) . '...'
        if length($text) > SHORT_DESCRIPTION_LENGTH;
    return $text;
}

lib/APISchema/Generator/Markdown/ResourceResolver.pm  view on Meta::CPAN


sub _collect_properties {
    my ($self, $path, $definition) = @_;
    return {} unless (ref $definition || '') eq 'HASH';

    my $ref = $definition->{'$ref'};
    if ($ref) {
        $ref = $ref =~ s/^#//r;
        my $def = JSON::Pointer->get($self->schema, $ref);
        return $self->_collect_properties($path, $def)
            if $def && $ref !~ qr!^/resource/[^/]+$!;

        $definition = +{
            %$definition,
            description => $definition->{description} // $def->{description},
        };
    }

    my $result = { _property_name(@$path) => $definition };
    _foreach_properties($path, $definition, sub {
        $result = +{
            %$result,
            %{$self->_collect_properties(@_)},
        };
    });
    return $result;
}

sub _collect_example {
    my ($self, $path, $definition) = @_;
    return ($definition->{example}, 1) if exists $definition->{example};

    if (my $union = $definition->{oneOf} || $definition->{anyOf} || $definition->{allOf}) {
        return ($self->_collect_example($path, $union->[0]), 1);
    }

    my $ref = $definition->{'$ref'};
    if ($ref) {
        $ref = $ref =~ s/^#//r;
        my $def = JSON::Pointer->get($self->schema, $ref);
        return ($self->_collect_example($path, $def), 1) if $def;
    }

    my %result;
    my $type = $definition->{type} || '';
    _foreach_properties($path, $definition, sub {
        my ($example, $exists) = $self->_collect_example(@_);
        unless ($exists) {
            if (exists $_[1]->{default}) {
                $example = $_[1]->{default};
                $exists = 1;
            }
        }
        $result{$_[0]->[-1]} = $example if $exists;
    });

    return (\%result, 1) if $type eq 'object';

    if ($type eq 'array') {
        return ([ $result{'[]'} ], 1) if $result{'[]'};

        my @result;
        for (keys %result) {
            next unless $_ =~ /\A\[([0-9]+)\]\z/;
            $result[$1] = $result{$_};
        }
        return (\@result, 1);
    }

    return (undef, 0);
}

sub properties {
    my ($self, $resource) = @_;
    return $self->_collect_properties([], $resource);
}

sub example {
    my ($self, $resource) = @_;
    my ($example) = $self->_collect_example([], $resource);
    return $example;
}

1;

lib/APISchema/Route.pm  view on Meta::CPAN

use strict;
use warnings;

# lib
use APISchema::Resource;

# cpan
use Class::Accessor::Lite (
    new => 1,
    rw => [qw(route title description destination method option
              request_resource response_resource)],
);

sub _canonical_resource {
    my ($self, $method, $resource_root, $extra_args, $filter) = @_;

    $method = "${method}_resource";
    my $resource = $self->$method();
    for (@$extra_args) {
        last unless $resource && ref $resource eq 'HASH';
        last unless $resource->{$_};
        $resource = $resource->{$_};
    }
    $resource = { body => $resource } unless ref $resource;

    $filter = [qw(header parameter body)] unless scalar @$filter;
    my %filter = map { $_ => 1 } grep { $resource->{$_} } @$filter;
    return +{
        %$resource,
        map {
            my $name = $resource->{$_};
            $_ => APISchema::Resource->new(
                title => $name,
                definition => ,+{
                    %$resource_root,
                    '$ref' => sprintf '#/resource/%s', $name,
                },
            );
        } grep { $filter{$_} } qw(header parameter body),
    };
}

sub canonical_request_resource {
    my ($self, $resource_root, $extra_args, $filter) = @_;
    return $self->_canonical_resource(
        request => $resource_root,
        $extra_args // [], $filter // [],
    );
}

sub canonical_response_resource {
    my ($self, $resource_root, $extra_args, $filter) = @_;
    return $self->_canonical_resource(
        response => $resource_root,
        $extra_args // [], $filter // [],
    );
}

sub responsible_code_is_specified {
    my ($self) = @_;
    my $res = $self->response_resource;
    return unless $res && ref $res;

    my @codes = sort grep { $_ =~ qr!\A[0-9]+\z! } keys %$res;
    return @codes > 0;
}

sub responsible_codes {
    my ($self) = @_;

    return [200] unless $self->responsible_code_is_specified;

    my $res = $self->response_resource;
    my @codes = sort grep { $_ =~ qr!\A[0-9]+\z! } keys %$res;
    return @codes ? [@codes] : [200];
}

sub default_responsible_code {
    my ($self) = @_;

    $self->responsible_codes->[0];
}

1;

lib/APISchema/Schema.pm  view on Meta::CPAN

use APISchema::Resource;

use Class::Accessor::Lite (
    rw => [qw(title description)],
);

sub new {
    my ($class) = @_;

    bless {
        resources => {},
        routes => [],
    }, $class;
}

sub register_resource {
    my ($self, $title, $definition) = @_;

    my $resource = APISchema::Resource->new(
        title => $title,
        definition => $definition,
    );
    $self->{resources}->{$title} = $resource;

    return $resource;
}

sub get_resources {
    my ($self) = @_;

    [ sort { $a->title cmp $b->title } values %{$self->{resources}} ];
}

sub get_resource_by_name {
    my ($self, $name) = @_;

    $self->{resources}->{$name || ''};
}

sub get_resource_root {
    my ($self) = @_;
    return +{
        resource   => +{ map {
            $_ => $self->{resources}->{$_}->definition;
        } keys %{$self->{resources}} },
        properties => {},
    };
}

sub _next_title_candidate {
    my ($self, $base_title) = @_;
    if ($base_title =~ /\(([0-9]+)\)$/) {
        my $index = $1 + 1;
        return $base_title =~ s/\([0-9]+\)$/($index)/r;
    } else {
        return $base_title . '(1)';
    }
}

sub register_route {
     my ($self, %values) = @_;

     # make fresh title
     my $title = $values{title} // $values{route} // 'empty_route';
     while ($self->get_route_by_name($title)) {
         $title = $self->_next_title_candidate($title);
     }

     my $route = APISchema::Route->new(
         %values,
         title => $title,
     );
     push @{$self->{routes}}, $route;

lib/APISchema/Validator.pm  view on Meta::CPAN

package APISchema::Validator;
use strict;
use warnings;
use 5.014;

# cpan
use Class::Load qw(load_class);
use Class::Accessor::Lite::Lazy (
    ro => [qw(fetch_resource_method)],
    ro_lazy => [qw(validator_class)],
);

# lib
use APISchema::Resource;
use APISchema::Validator::Decoder;
use APISchema::Validator::Result;

use constant +{
    DEFAULT_VALIDATOR_CLASS => 'Valiemon',

lib/APISchema/Validator.pm  view on Meta::CPAN

    return DEFAULT_VALIDATOR_CLASS;
}

sub _new {
    my $class = shift;
    return bless { @_ == 1 && ref($_[0]) eq 'HASH' ? %{$_[0]} : @_ }, $class;
}

sub for_request {
    my $class = shift;
    return $class->_new(@_, fetch_resource_method => 'canonical_request_resource');
}

sub for_response {
    my $class = shift;
    return $class->_new(@_, fetch_resource_method => 'canonical_response_resource');
}

sub _valid_result { APISchema::Validator::Result->new_valid(@_) }
sub _error_result { APISchema::Validator::Result->new_error(@_) }

sub _resolve_encoding {
    my ($content_type, $encoding_spec) = @_;
    # TODO handle charset?
    $content_type = $content_type =~ s/\s*;.*$//r;
    $encoding_spec //= DEFAULT_ENCODING_SPEC;

    if (ref $encoding_spec) {
        $encoding_spec = $encoding_spec->{$content_type};
        return ( undef, { message => "Wrong content-type: $content_type" } )
            unless $encoding_spec;
    }

lib/APISchema/Validator.pm  view on Meta::CPAN

    return { message => "Failed to parse $decode" } if $@;

    my $validator = $validator_class->new($spec->definition);
    my ($valid, $err) = $validator->validate($obj);

    return {
        attribute => $err->attribute,
        position  => $err->position,
        expected  => $err->expected,
        actual    => $err->actual,
        message   => "Contents do not match resource '@{[$spec->title]}'",
    } unless $valid;

    return; # avoid returning the last conditional value
}

sub validate {
    my ($self, $route_name, $target, $schema) = @_;

    my @target_keys = @{+TARGETS};
    my $valid = _valid_result(@target_keys);

    my $route = $schema->get_route_by_name($route_name)
        or return $valid;
    my $method = $self->fetch_resource_method;
    my $resource_root = $schema->get_resource_root;
    my $resource_spec = $route->$method(
        $resource_root,
        $target->{status_code} ? [ $target->{status_code} ] : [],
        [ @target_keys ],
    );
    @target_keys = grep { $resource_spec->{$_} } @target_keys;

    my $body_encoding = $resource_spec->{body} && do {
        my ($enc, $err) = _resolve_encoding(
            $target->{content_type} // '',
            $resource_spec->{encoding},
        );
        if ($err) {
            return _error_result(body => $err);
        }
        $enc;
    };

    my $encoding = {
        body      => $body_encoding,
        parameter => 'url_parameter',
        header    => 'perl',
    };

    my $validator_class = $self->validator_class;
    load_class $validator_class;
    my $result = APISchema::Validator::Result->new;
    $result->merge($_) for map {
        my $field = $_;
        my $err = _validate($validator_class, map { $_->{$field} } (
            $encoding, $target, $resource_spec,
        ));
        $err ? _error_result($field => {
            %$err,
            encoding => $encoding->{$_},
        }) : _valid_result($field);
    } @target_keys;

    return $result;
}

1;
__END__

lib/Plack/App/APISchema/MockServer.pm  view on Meta::CPAN

    my ($self, $env) = @_;

    my $req = Plack::Request->new($env);

    my ($matched, $router_simple_route) = $self->router->routematch($env);

    unless ($matched) {
        return [404, ['Content-Type' => 'text/plain; charset=utf-8'], ['not found']];
    }

    my $root = $self->schema->get_resource_root;

    my $route = $self->schema->get_route_by_name($router_simple_route->name);

    my $default_code = $route->default_responsible_code;
    my $response_resource = $route->canonical_response_resource($root, [
        $default_code
    ]);

    my $resolver = APISchema::Generator::Markdown::ResourceResolver->new(schema => $root);

    my $formatter = APISchema::Generator::Markdown::ExampleFormatter->new(
        resolver => $resolver,
        spec     => $response_resource,
    );

    # TODO: serve all headers defined in example
    # TODO: format body with encoding
    return [$default_code, ['Content-Type' => 'application/json; charset=utf-8'], [encode_utf8($formatter->body)]];
}

sub router {
    my ($self) = @_;

lib/Plack/App/APISchema/MockServer.pm  view on Meta::CPAN


Plack::App::APISchema::MockServer - Mock Server for APISchema

=head1 SYNOPSIS

  use Plack::App::APISchema::MockServer;
  my $app = Plack::App::APISchema::MockServer->new($schema)->to_app;

=head1 DESCRIPTION

Plack::App::APISchema::MockServer mocks response with example of resource definitions.

lib/Plack/Middleware/APISchema/RequestValidator.pm  view on Meta::CPAN

sub call {
    my ($self, $env) = @_;
    my $req = Plack::Request->new($env);

    my ($matched, $route) = $self->router->routematch($env);
    $matched or return $self->app->($env);

    my $validator = APISchema::Validator->for_request(
        validator_class => $self->validator // DEFAULT_VALIDATOR_CLASS,
    );
    my $result = $validator->validate($route->name => {
        header => +{ map {
            my $field = lc($_) =~ s/[-]/_/gr;
            ( $field => $req->header($_) );
        } $req->headers->header_field_names },
        parameter => $env->{QUERY_STRING},
        body => $req->content,
        content_type => $req->content_type,
    }, $self->schema);

    my $errors = $result->errors;
    my $status_code = $self->_resolve_status_code($result);
    return [
        $status_code,
        [ 'Content-Type' => 'application/json' ],
        [ encode_json_canonical($errors) ],
    ] if scalar keys %$errors;

    $self->app->($env);
}

sub router {
    my ($self) = @_;

    $self->{router} //= do {
        my $generator = APISchema::Generator::Router::Simple->new;
        $generator->generate_router($self->schema);
    };
}

sub _resolve_status_code {
    my ($self, $validation_result) = @_;
    my $error_message = $validation_result->errors->{body}->{message} // '';
    return $error_message =~ m/Wrong content-type/ ? HTTP_UNSUPPORTED_MEDIA_TYPE : HTTP_UNPROCESSABLE_ENTITY;
}


1;

lib/Plack/Middleware/APISchema/ResponseValidator.pm  view on Meta::CPAN

use Plack::Response;
use APISchema::Generator::Router::Simple;
use APISchema::Validator;
use APISchema::JSON;

use constant DEFAULT_VALIDATOR_CLASS => 'Valiemon';

sub call {
    my ($self, $env) = @_;

    Plack::Util::response_cb($self->app->($env), sub {
        my $res = shift;

        my ($matched, $route) = $self->router->routematch($env);
        $matched or return;

        my $plack_res = Plack::Response->new(@$res);
        my $body;
        Plack::Util::foreach($res->[2] // [], sub { $body .= $_[0] });

        my $validator_class = $self->validator // DEFAULT_VALIDATOR_CLASS;
        my $validator = APISchema::Validator->for_response(
            validator_class => $validator_class,
        );
        my $result = $validator->validate($route->name => {
            status_code => $res->[0],
            header => +{ map {
                my $field = lc($_) =~ s/[-]/_/gr;
                ( $field => $plack_res->header($_) );
            } $plack_res->headers->header_field_names },
            body => $body,
            content_type => scalar $plack_res->content_type,
        }, $self->schema);

        my $errors = $result->errors;
        if (scalar keys %$errors) {
            my $error_cause = join '+', __PACKAGE__, $validator_class;
            @$res = (
                500,
                [ 'Content-Type' => 'application/json', 'X-Error-Cause' => $error_cause ],
                [ encode_json_canonical($errors) ],
            );
            return;
        }

        $res->[2] = [ $body ];
    });
}

sub router {
    my ($self) = @_;

    $self->{router} //= do {
        my $generator = APISchema::Generator::Router::Simple->new;
        $generator->generate_router($self->schema);
    };

script/generate_markdown_document.pl  view on Meta::CPAN

#!/usr/bin/env perl
use strict;
use warnings;
use Encode qw(encode_utf8);

BEGIN {
    # cpan
    use Path::Class qw(file);
    my $Root = file(__FILE__)->dir->parent->resolve->absolute;
    unshift @INC, $Root->subdir('lib').q();
}

# lib
use APISchema::DSL;
use APISchema::Generator::Markdown;

unless ($ARGV[0]) {
    print <<EOM;
Usage: $0 <file>

t/APISchema-DSL.t  view on Meta::CPAN


    dies_ok {
        title 'test';
    };

    dies_ok {
        description 'test';
    };

    dies_ok {
        resource 'test' => ();
    };

    dies_ok {
        GET '/' => ();
    };

    dies_ok {
        POST '/' => ();
    };

t/APISchema-DSL.t  view on Meta::CPAN

            };
        };
    };

    subtest 'Validation should be returned' => sub {
        lives_ok {
            my $schema = APISchema::DSL::process {
                title 'BMI API';
                description 'The API to calculate BMI';

                resource figure => {
                    type => 'object',
                    description => 'Figure, which includes weight and height',
                    properties => {
                        weight  => {
                            type => 'number',
                            description => 'Weight(kg)',
                            example => 50,
                        },
                        height  => {
                            type => 'number',
                            description => 'Height(m)',
                            example => 1.6,
                        },
                    },
                    required => ['weight', 'height'],
                };

                resource bmi => {
                    type => 'object',
                    description => 'Body mass index',
                    properties => {
                        value  => {
                            type => 'number',
                            description => 'bmi value',
                            example => 19.5,
                        },
                    },
                    required => ['value'],
                };

                POST '/bmi' => {
                    title           => 'BMI API',
                    description     => 'This API calculates your BMI.',
                    destination     => {
                        controller  => 'BMI',
                        action      => 'calculate',
                    },
                    request         => 'figure',
                    response        => 'bmi',
                }, {
                    on_match => sub { 1 },
                };
            };
            isa_ok $schema, 'APISchema::Schema';

            is_deeply [ sort {
                $a->title cmp $b->title;
            } @{$schema->get_resources} ], [ {
                title => 'bmi',
                definition => {
                    type => 'object',
                    description => 'Body mass index',
                    properties => {
                        value  => {
                            type => 'number',
                            description => 'bmi value',
                            example => 19.5,
                        },

t/APISchema-DSL.t  view on Meta::CPAN

            is scalar @$routes, 1;

            is $routes->[0]->route, '/bmi';
            is $routes->[0]->title, 'BMI API';
            is $routes->[0]->description, 'This API calculates your BMI.';
            is_deeply $routes->[0]->destination, {
                controller => 'BMI',
                action     => 'calculate',
            };
            cmp_deeply $routes->[0]->option, { on_match => code(sub { 1 }) };
            is $routes->[0]->request_resource, 'figure';
            is $routes->[0]->response_resource, 'bmi';
        };
    };
}

sub from_file : Tests {
    lives_ok {
        my $schema = APISchema::DSL::process {
            include 't/fixtures/bmi.def';
        };

        isa_ok $schema, 'APISchema::Schema';

        is $schema->title, 'BMI API';
        is $schema->description, 'The API to calculate BMI';

        is_deeply [ sort {
            $a->title cmp $b->title;
        } @{$schema->get_resources} ], [ {
            title => 'bmi',
            definition => {
                type => 'object',
                description => 'Body mass index',
                properties => {
                    value  => {
                        type => 'number',
                        description => 'bmi value',
                        example => 19.5,
                    },

t/APISchema-DSL.t  view on Meta::CPAN

        is scalar @$routes, 1;

        is $routes->[0]->route, '/bmi';
        is $routes->[0]->title, 'BMI API';
        is $routes->[0]->description, 'This API calculates your BMI.';
        is_deeply $routes->[0]->destination, {
            controller => 'BMI',
            action     => 'calculate',
        };
        cmp_deeply $routes->[0]->option, { on_match => code(sub { 1 }) };
        is $routes->[0]->request_resource, 'figure';
        is $routes->[0]->response_resource, 'bmi';
    };

    dies_ok {
        my $schema = APISchema::DSL::process {
            include 'not-such-file';
        };
    };

    dies_ok {
        my $schema = APISchema::DSL::process {
            include 't/fixtures/syntax-error.def';
        };
    };

    dies_ok {
        my $schema = APISchema::DSL::process {
            include 't/fixtures/runtime-error.def';
        };
    };
}

sub with_unicode : Tests {
    my $schema = APISchema::DSL::process {
        include 't/fixtures/user.def';
    };

    isa_ok $schema, 'APISchema::Schema';

    is $schema->title, decode_utf8('ユーザー');
    is $schema->description, decode_utf8('ユーザーの定義');

    cmp_deeply $schema->get_resource_by_name('user')->{definition}, {
        type => 'object',
        description => decode_utf8('ユーザー'),
        properties => {
            first_name  => {
                type => 'string',
                description => decode_utf8('å§“'),
                example => decode_utf8('小飼'),
            },
            last_name  => {
                type => 'string',

t/APISchema-Generator-Markdown-Formatter.t  view on Meta::CPAN

package t::APISchema::Generator::Markdown::Formatter;
use lib '.';
use t::test;
use t::test::fixtures;

use APISchema::Generator::Markdown::Formatter ();

sub _type : Tests {
    for my $case (
        [{} => 'undefined'],
        [{type => 'object'} => '`object`'],
        [{type => ['object', 'number']} =>  '`"object"`&#124;`"number"`'],
        [{'$ref' => '#/resource/foo'} =>  '[`foo`](#resource-foo)'],
        [{oneOf => [{ type =>'object'}, {type =>'number'}]} =>  '`object`&#124;`number`'],
        [{type => 'string', enum => ['a', 'b', 'c']} =>  '`"a"`&#124;`"b"`&#124;`"c"`'],
        [{type => 'number', enum => [1, 2, 3]} =>  '`1`&#124;`2`&#124;`3`'],
    ) {
       is APISchema::Generator::Markdown::Formatter::type($case->[0]), $case->[1], $case->[2] || $case->[1];
    }
}

t/APISchema-Generator-Markdown.t  view on Meta::CPAN

package t::APISchema::Generator::Markdown;
use lib '.';
use t::test;
use t::test::fixtures;
use utf8;

use APISchema::DSL;

sub _require : Test(startup => 1) {
    my ($self) = @_;

    use_ok 'APISchema::Generator::Markdown';
}

sub instantiate : Tests {
    my $generator = APISchema::Generator::Markdown->new;
    isa_ok $generator, 'APISchema::Generator::Markdown';
}

sub generate : Tests {
    subtest 'Simple' => sub {
        my $schema = t::test::fixtures::prepare_bmi;

        my $generator = APISchema::Generator::Markdown->new;
        my $markdown = $generator->format_schema($schema);

        like $markdown, qr{# BMI API};
        like $markdown, qr{^\Q    - [BMI API](#route-BMI%20API) - `POST` /bmi\E$}m;
        like $markdown, qr!{"height":1.6,"weight":50}!;
        like $markdown, qr!|`.` |`object` | | |`required["value"]` |Body mass index |!;
        like $markdown, qr!|`.height` |`number` | |`1.6` | |Height(m) |!;
    };

    subtest 'Complex' => sub {
        my $schema = t::test::fixtures::prepare_family;

        my $generator = APISchema::Generator::Markdown->new;
        my $markdown = $generator->format_schema($schema);

        like $markdown, qr{# Family API};
        like $markdown, qr!GET /person[?]name=Alice!;
        like $markdown, qr!{"message":"OK","status":"success"}!;
        like $markdown, qr![{"age":16,"name":"Alice"},{"age":14,"name":"Charlie"}]!;
        my $text1 = <<EOS;
|`.` |`array` | |`[{"age":16,"name":"Alice"},{"age":14,"name":"Charlie"}]` | |Some people |
|`.[]` |[`person`](#resource-person) | | | |A person |
EOS
        like $markdown, qr!\Q$text1\E!;
        like $markdown, qr!|`.\[\]` |[`person`](#resource-person) | | | | |!;
        my $text2 = <<EOS;
200 OK
[{"age":16,"name":"Alice"},{"age":14,"name":"Charlie"}]
EOS
        like $markdown, qr!\Q$text2\E!;
    };

    subtest 'Status switch' => sub {
        my $schema = t::test::fixtures::prepare_status;

        my $generator = APISchema::Generator::Markdown->new;
        my $markdown = $generator->format_schema($schema);
        like $markdown, qr{#### Response `200 OK`};
        like $markdown, qr{\nHTTP/1.1 200 OK\nSucceeded!\n};
        like $markdown, qr{#### Response `400 Bad Request`};
    };

    subtest 'example with no containers' => sub {
        my $schema = APISchema::DSL::process {
          resource gender => {
            enum => ['male', 'female', 'other'],
            example => 'other',
          };
        };

        my $generator = APISchema::Generator::Markdown->new;
        my $markdown = $generator->format_schema($schema);

        like $markdown, qr/^"other"$/m;
    };

t/APISchema-Generator-Markdown.t  view on Meta::CPAN


        my $generator = APISchema::Generator::Markdown->new;
        my $markdown = $generator->format_schema($schema);

        like $markdown, qr{\Q- [Fetch](#route-Fetch) - `GET`, `HEAD` /\E}, 'FETCH expanded to GET and HEAD';
    };
}

sub generate_utf8 : Tests {
    subtest 'Simple' => sub {
        my $schema = t::test::fixtures::prepare_user;

        my $generator = APISchema::Generator::Markdown->new;
        my $markdown = $generator->format_schema($schema);

        like $markdown, qr!{\n   "first_name" : "小飼",\n   "last_name" : "弾"\n}!;
        like $markdown, qr!\Q|`.last_name` |`string` | |`"弾"` | |名 |\E!;
    };
}

sub boolean : Tests {
    my $schema = t::test::fixtures::prepare_boolean;

    my $generator = APISchema::Generator::Markdown->new;
    my $markdown = $generator->format_schema($schema);

    like $markdown, qr!\btrue\b!;
}

sub example_null : Tests {
    my $schema = t::test::fixtures::prepare_example_null;

    my $generator = APISchema::Generator::Markdown->new;
    my $markdown = $generator->format_schema($schema);

    like $markdown, qr!"value" : null!;
    like $markdown, qr!\Q|`.value` |`null` | |`null` | |The Value |\E!;
}

t/APISchema-Generator-Router-Simple.t  view on Meta::CPAN

package t::APISchema::Generator::Router::Simple;
use lib '.';
use t::test;
use t::test::fixtures;
use APISchema::Schema;
use Router::Simple;

sub _require : Test(startup => 1) {
    my ($self) = @_;

    use_ok 'APISchema::Generator::Router::Simple';
}

sub instantiate : Tests {
    my $generator = APISchema::Generator::Router::Simple->new;
    isa_ok $generator, 'APISchema::Generator::Router::Simple';
}

sub generate : Tests {
    my $schema = t::test::fixtures::prepare_bmi;

    my $generator = APISchema::Generator::Router::Simple->new;
    my $router = $generator->generate_router($schema);

    isa_ok $router, 'Router::Simple';

    cmp_deeply $router->match({ PATH_INFO => '/bmi', HTTP_HOST => 'localhost', REQUEST_METHOD => 'POST' } ), {
        controller      => 'BMI',
        action          => 'calculate',
    };

    note $router->as_string;
}

sub inject_routes : Tests {
    my $schema = t::test::fixtures::prepare_bmi;

    my $router = Router::Simple->new;
    $router->connect('/', {controller => 'Root', action => 'show'});

    my $generator = APISchema::Generator::Router::Simple->new;
    my $returned_router = $generator->inject_routes($schema => $router);

    is $returned_router, $router;

    isa_ok $router, 'Router::Simple';

t/APISchema-Resource.t  view on Meta::CPAN

use lib '.';
use t::test;

sub _require : Test(startup => 1) {
    my ($self) = @_;

    use_ok 'APISchema::Resource';
}

sub instantiate : Tests {
    my $resource = APISchema::Resource->new(
        title => 'Human',
        definition => {
            type => 'object',
            properties => {
                name  => { type => 'string'  },
                age => { type => 'integer' },
            },
            required => ['name', 'age'],
        },
    );
    cmp_deeply $resource, isa('APISchema::Resource') & methods(
        title => 'Human',
        definition => {
            type => 'object',
            properties => {
                name  => { type => 'string'  },
                age => { type => 'integer' },
            },
            required => ['name', 'age'],
        },
    );

t/APISchema-Route.t  view on Meta::CPAN

sub instantiate : Tests {
    my $route = APISchema::Route->new(
        route             => '/bmi/',
        title             => 'BMI API',
        description       => 'This API calculates your BMI.',
        destination       => {
            controller    => 'BMI',
            action        => 'calculate',
        },
        method            => 'POST',
        request_resource  => 'health',
        response_resource => 'bmi',
    );
    cmp_deeply $route, isa('APISchema::Route') & methods(
        route             => '/bmi/',
        title             => 'BMI API',
        description       => 'This API calculates your BMI.',
        destination       => {
            controller    => 'BMI',
            action        => 'calculate',
        },
        method            => 'POST',
        request_resource  => 'health',
        response_resource => 'bmi',
    );
}

sub responsible_codes : Tests {
    subtest 'when simple response resource' => sub {
        my $route = APISchema::Route->new(
            route             => '/bmi/',
            title             => 'BMI API',
            description       => 'This API calculates your BMI.',
            destination       => {
                controller    => 'BMI',
                action        => 'calculate',
            },
            method            => 'POST',
            request_resource  => 'health',
            response_resource => 'bmi',
        );
        cmp_deeply $route->responsible_codes, [200];
        is $route->default_responsible_code, 200;
        ok ! $route->responsible_code_is_specified;
    };

    subtest 'when multiple response codes are specified' => sub {
        my $route = APISchema::Route->new(
            route             => '/bmi/',
            title             => 'BMI API',
            description       => 'This API calculates your BMI.',
            destination       => {
                controller    => 'BMI',
                action        => 'calculate',
            },
            method            => 'POST',
            request_resource  => 'health',
            response_resource => {
                201 => 'bmi',
                401 => 'bmi',
                400 => 'bmi',
            },
        );
        is $route->default_responsible_code, 201;
        ok $route->responsible_code_is_specified;
    };

}

t/APISchema-Schema.t  view on Meta::CPAN

    my ($self) = @_;

    use_ok 'APISchema::Schema';
}

sub instantiate : Tests {
    my $schema = APISchema::Schema->new;
    isa_ok $schema, 'APISchema::Schema';
}

sub resource : Tests {
    my $schema = APISchema::Schema->new;

    is $schema->get_resource_by_name('user'), undef;

    cmp_deeply $schema->get_resources, [];

    $schema->register_resource('user' => {
        type => 'object',
        properties => {
            name  => { type => 'string'  },
            age => { type => 'integer' },
        },
        required => ['name', 'age'],
    });

    cmp_deeply $schema->get_resource_by_name('user'), isa('APISchema::Resource') & methods(
        title => 'user',
        definition => {
            type => 'object',
            properties => {
                name  => { type => 'string'  },
                age => { type => 'integer' },
            },
            required => ['name', 'age'],
        },
    );

    is $schema->get_resource_by_name('not_user'), undef;

    cmp_deeply $schema->get_resources, [
        $schema->get_resource_by_name('user'),
    ];
}

sub route : Tests {
    subtest 'Basic' => sub {
        my $schema = APISchema::Schema->new;
        cmp_deeply $schema->get_routes, [];

        $schema->register_route(
            route             => '/bmi/',
            description       => 'This API calculates your BMI.',
            destination       => {
                controller    => 'BMI',
                action        => 'calculate',
            },
            method            => 'POST',
            request_resource  => 'health',
            response_resource => 'bmi',
        );

        cmp_deeply $schema->get_routes, [
            isa('APISchema::Route') & methods(
                route             => '/bmi/',
                description       => 'This API calculates your BMI.',
                destination       => {
                    controller    => 'BMI',
                    action        => 'calculate',
                },
                method            => 'POST',
                request_resource  => 'health',
                response_resource => 'bmi',
            ),
        ];
    };

    subtest 'Naming' => sub {
        my $schema = APISchema::Schema->new;
        cmp_deeply $schema->get_routes, [];

        $schema->register_route(
            title => 'BMI API',

t/APISchema-Validator.t  view on Meta::CPAN

package t::Plack::Middleware::APISchema::ResponseValidator;
use lib '.';
use t::test;
use t::test::fixtures;
use JSON::XS qw(encode_json);

sub _require : Test(startup => 1) {
    use_ok 'APISchema::Validator';
}

sub instantiate : Tests {
    subtest 'For request' => sub {
        my $validator = APISchema::Validator->for_request;
        isa_ok $validator, 'APISchema::Validator';
        is $validator->validator_class, 'Valiemon';
        is $validator->fetch_resource_method, 'canonical_request_resource';
    };

    subtest 'For response' => sub {
        my $validator = APISchema::Validator->for_response;
        isa_ok $validator, 'APISchema::Validator';
        is $validator->validator_class, 'Valiemon';
        is $validator->fetch_resource_method, 'canonical_response_resource';
    };

    subtest 'Result' => sub {
        my $r = APISchema::Validator::Result->new;
        isa_ok $r, 'APISchema::Validator::Result';

        my $valid = APISchema::Validator::Result->new_valid;
        isa_ok $valid, 'APISchema::Validator::Result';

        my $error = APISchema::Validator::Result->new_valid;
        isa_ok $error, 'APISchema::Validator::Result';
    };
}

sub result : Tests {
    subtest 'empty' => sub {
        my $r = APISchema::Validator::Result->new;
        ok $r->is_valid;
        is_deeply $r->errors, {};
    };

    subtest 'valid without target' => sub {
        my $r = APISchema::Validator::Result->new_valid;
        ok $r->is_valid;
        is_deeply $r->errors, {};

t/APISchema-Validator.t  view on Meta::CPAN

        ok !$r->is_valid;
        is_deeply $r->errors, { foo => 3, bar => 1 };
    };
}

sub _simple_route ($$) {
    my ($schema, $keys)  =  @_;
    $keys = [qw(header parameter body)] unless defined $keys;
    $schema->register_route(
        route => '/endpoint',
        request_resource => {
            map { $_ => 'figure' } @$keys
        },
        response_resource => {
            map { $_ => 'bmi' } @$keys
        },
    );
    return $schema;
}

sub _forced_route ($$) {
    my ($schema, $keys)  =  @_;
    $keys = [qw(header parameter body)] unless defined $keys;
    $schema->register_route(
        route => '/endpoint',
        request_resource => {
            encoding => 'json',
            map { $_ => 'figure' } @$keys
        },
        response_resource => {
            encoding => 'json',
            map { $_ => 'bmi' } @$keys
        },
    );
    return $schema;
}

sub _invalid_encoding_route ($$) {
    my ($schema, $keys)  =  @_;
    $keys = [qw(header parameter body)] unless defined $keys;
    $schema->register_route(
        route => '/endpoint',
        request_resource => {
            encoding => 'hoge',
            map { $_ => 'figure' } @$keys
        },
        response_resource => {
            encoding => 'hoge',
            map { $_ => 'bmi' } @$keys
        },
    );
    return $schema;
}

sub _strict_route ($$) {
    my ($schema, $keys)  =  @_;
    $keys = [qw(header parameter body)] unless defined $keys;
    $schema->register_route(
        route => '/endpoint',
        request_resource => {
            encoding => { 'application/json' => 'json' },
            map { $_ => 'figure' } @$keys
        },
        response_resource => {
            encoding => { 'application/json' => 'json' },
            map { $_ => 'bmi' } @$keys
        },
    );
    return $schema;
}

sub validate_request : Tests {
    subtest 'valid with emtpy schema' => sub {
        my $schema = APISchema::Schema->new;
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            header => { foo => 'bar' },
            parameter => 'foo&bar',
            body => '{"foo":"bar"}',
            content_type => 'application/json',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'valid with empty target' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, [];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {}, $schema);
        ok $result->is_valid;
    };

    subtest 'valid with some target and schema' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({weight => 50, height => 1.6}),
            content_type => 'application/json',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'invalid with missing property' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({weight => 50}),
            content_type => 'application/json',
        }, $schema);
        ok !$result->is_valid;
        is_deeply [ keys %{$result->errors} ], [ 'body' ];
        is_deeply [ map { $_->{attribute} } values %{$result->errors} ],
            [ ('Valiemon::Attributes::Required') ];
        is_deeply [ map { $_->{encoding} } values %{$result->errors} ],
            [ ('json') ];
    };

    subtest 'invalid without body' => sub {
        for my $value ({}, '', undef) {
            my $schema = _simple_route t::test::fixtures::prepare_bmi, ['body'];
            my $validator = APISchema::Validator->for_request;
            my $result = $validator->validate('/endpoint' => {
                body => $value,
            }, $schema);
            ok ! $result->is_valid;
            is_deeply [ keys %{$result->errors} ], [ 'body' ];
        }
    };

    subtest 'invalid without parameter' => sub {
        for my $value ({}, '', undef) {
            my $schema = _simple_route t::test::fixtures::prepare_bmi, ['parameter'];
            my $validator = APISchema::Validator->for_request;
            my $result = $validator->validate('/endpoint' => {
                parameter => $value,
            }, $schema);
            ok ! $result->is_valid;
            is_deeply [ keys %{$result->errors} ], [ 'parameter' ];
        }
    };


    subtest 'invalid with wrong encoding' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({weight => 50, height => 1.6}),
            content_type => 'application/x-www-form-urlencoded',
        }, $schema);
        ok !$result->is_valid;
        is_deeply [ keys %{$result->errors} ], [ 'body' ];
        is_deeply [ map { $_->{attribute} } values %{$result->errors} ],
            [ ('Valiemon::Attributes::Required') ];
        is_deeply [ map { $_->{encoding} } values %{$result->errors} ],
            [ ('url_parameter') ];
    };

    subtest 'invalid with invalid encoding' => sub {
        my $schema = _invalid_encoding_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({weight => 50, height => 1.6}),
            content_type => 'application/json',
        }, $schema);
        ok !$result->is_valid;
        is_deeply [ keys %{$result->errors} ], [ 'body' ];
        is_deeply [ map { $_->{message} } values %{$result->errors} ],
            [ ('Unknown decoding method: hoge') ];
    };

    subtest 'valid with forced encoding' => sub {
        my $schema = _forced_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({weight => 50, height => 1.6}),
            content_type => 'application/x-www-form-urlencoded',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'valid with strict content-type check' => sub {
        my $schema = _strict_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({weight => 50, height => 1.6}),
            content_type => 'application/json',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'invalid with wrong content type' => sub {
        my $schema = _strict_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_request;
        my $content_type = 'application/x-www-form-urlencoded';
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({weight => 50, height => 1.6}),
            content_type => $content_type,
        }, $schema);
        ok !$result->is_valid;
        is_deeply [ keys %{$result->errors} ], [ 'body' ];
        is_deeply [ map { $_->{message} } values %{$result->errors} ],
            [ ("Wrong content-type: $content_type") ];
    };

    subtest 'valid parameter' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['parameter'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            parameter => 'weight=50&height=1.6',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'invalid parameter' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['parameter'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            parameter => 'weight=50',
        }, $schema);
        ok !$result->is_valid;
        is_deeply [ map { $_->{attribute} } values %{$result->errors} ],
            [ ('Valiemon::Attributes::Required') ];
        is_deeply [ map { $_->{encoding} } values %{$result->errors} ],
            [ ('url_parameter') ];
    };

    subtest 'valid header' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['header'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            header => { weight => 50, height => 1.6 },
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'invalid header' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['header'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            header => { weight => 50 },
        }, $schema);
        ok !$result->is_valid;
        is_deeply [ keys %{$result->errors} ], [ 'header' ];
        is_deeply [ map { $_->{attribute} } values %{$result->errors} ],
            [ ('Valiemon::Attributes::Required') ];
        is_deeply [ map { $_->{encoding} } values %{$result->errors} ],
            [ ('perl') ];
    };

    subtest 'all valid' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['body', 'parameter', 'header'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            header => { weight => 50, height => 1.6 },
            parameter => 'weight=50&height=1.6',
            body => encode_json({weight => 50, height => 1.6}),
            content_type => 'application/json',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'many invalid' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['body', 'parameter', 'header'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('/endpoint' => {
            header => { weight => 50 },
            parameter => 'weight=50',
            body => encode_json({weight => 50}),
            content_type => 'application/json',
        }, $schema);
        ok !$result->is_valid;
        is scalar keys %{$result->errors}, 3;
        is_deeply [ sort keys %{$result->errors} ],
            [ qw(body header parameter) ];
        is_deeply [ map { $_->{attribute} } values %{$result->errors} ],
            [ ('Valiemon::Attributes::Required') x 3 ];
        is_deeply [ sort map { $_->{encoding} } values %{$result->errors} ],
            [ ('json', 'perl', 'url_parameter') ];
    };
}

sub validate_response : Tests {
    subtest 'valid with emtpy schema' => sub {
        my $schema = APISchema::Schema->new;
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {
            header => { foo => 'bar' },
            body => '{"foo":"bar"}',
            content_type => 'application/json',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'valid with empty target' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, [];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {}, $schema);
        ok $result->is_valid;
    };

    subtest 'valid with some target and schema' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({value => 19.5}),
            content_type => 'application/json',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'invalid with missing property' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({hoge => 'foo'}),
            content_type => 'application/json',
        }, $schema);
        ok !$result->is_valid;
        is_deeply [ keys %{$result->errors} ], [ 'body' ];
        is_deeply [ map { $_->{attribute} } values %{$result->errors} ],
            [ ('Valiemon::Attributes::Required') ];
        is_deeply [ map { $_->{encoding} } values %{$result->errors} ],
            [ ('json') ];
    };

    subtest 'invalid with wrong encoding' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({value => 19.5}),
            content_type => 'application/x-www-form-urlencoded',
        }, $schema);
        ok !$result->is_valid;
        is_deeply [ keys %{$result->errors} ], [ 'body' ];
        is_deeply [ map { $_->{attribute} } values %{$result->errors} ],
            [ ('Valiemon::Attributes::Required') ];
        is_deeply [ map { $_->{encoding} } values %{$result->errors} ],
            [ ('url_parameter') ];
    };

    subtest 'invalid with invalid encoding' => sub {
        my $schema = _invalid_encoding_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({value => 19.5}),
            content_type => 'application/json',
        }, $schema);
        ok !$result->is_valid;
        is_deeply [ keys %{$result->errors} ], [ 'body' ];
        is_deeply [ map { $_->{message} } values %{$result->errors} ],
            [ ('Unknown decoding method: hoge') ];
    };

    subtest 'valid with forced encoding' => sub {
        my $schema = _forced_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({value => 19.5}),
            content_type => 'application/x-www-form-urlencoded',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'valid with strict content-type check' => sub {
        my $schema = _strict_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({value => 19.5}),
            content_type => 'application/json',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'invalid with wrong content type' => sub {
        my $schema = _strict_route t::test::fixtures::prepare_bmi, ['body'];
        my $validator = APISchema::Validator->for_response;
        my $content_type = 'application/x-www-form-urlencoded';
        my $result = $validator->validate('/endpoint' => {
            body => encode_json({value => 19.5}),
            content_type => $content_type,
        }, $schema);
        ok !$result->is_valid;
        is_deeply [ keys %{$result->errors} ], [ 'body' ];
        is_deeply [ map { $_->{message} } values %{$result->errors} ],
            [ ("Wrong content-type: $content_type") ];
    };

    subtest 'valid header' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['header'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {
            header => { value => 19.5 },
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'invalid header' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['header'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {
            header => {},
        }, $schema);
        ok !$result->is_valid;
        is_deeply [ keys %{$result->errors} ], [ 'header' ];
        is_deeply [ map { $_->{attribute} } values %{$result->errors} ],
            [ ('Valiemon::Attributes::Required') ];
        is_deeply [ map { $_->{encoding} } values %{$result->errors} ],
            [ ('perl') ];
    };

    subtest 'all valid' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['body', 'header'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {
            header => { value => 19.5 },
            body => encode_json({value => 19.5}),
            content_type => 'application/json',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'many invalid' => sub {
        my $schema = _simple_route t::test::fixtures::prepare_bmi, ['body', 'header'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('/endpoint' => {
            header => {},
            body => encode_json({}),
            content_type => 'application/json',
        }, $schema);
        ok !$result->is_valid;
        is scalar keys %{$result->errors}, 2;
        is_deeply [ sort keys %{$result->errors} ],
            [ qw(body header) ];
        is_deeply [ map { $_->{attribute} } values %{$result->errors} ],
            [ ('Valiemon::Attributes::Required') x 2 ];
        is_deeply [ sort map { $_->{encoding} } values %{$result->errors} ],
            [ ('json', 'perl') ];
    };

    subtest 'valid referenced resource' => sub {
        my $schema = _forced_route t::test::fixtures::prepare_family, ['body'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('Children GET API' => {
            body => encode_json([ {
                name => 'Alice',
                age  => 16,
            }, {
                name => 'Charlie',
                age  => 14,
            } ]),
            content_type => 'application/json',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'invalid referenced resource' => sub {
        my $schema = _forced_route t::test::fixtures::prepare_family, ['body'];
        my $validator = APISchema::Validator->for_response;
        my $result = $validator->validate('Children GET API' => {
            body => encode_json([ {
                name => 'Alice',
                age  => 16,
            }, {
                age  => 14,
            } ]),
            content_type => 'application/json',
        }, $schema);
        ok !$result->is_valid;
    };

 SKIP: {
    skip 'Recursive dereference is not implemented in Valiemon', 2;
    subtest 'valid recursively referenced resource' => sub {
        my $schema = _forced_route t::test::fixtures::prepare_family, ['body'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('Children GET API' => {
            parameter => 'name=Bob',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'invalid recursively referenced resource' => sub {
        my $schema = _forced_route t::test::fixtures::prepare_family, ['body'];
        my $validator = APISchema::Validator->for_request;
        my $result = $validator->validate('Children GET API' => {
            parameter => 'person=Bob',
        }, $schema);
        ok !$result->is_valid;
    };

    };
}

sub status : Tests {
    my $schema = t::test::fixtures::prepare_status;
    my $validator = APISchema::Validator->for_response;

    subtest 'Status 200 with valid body' => sub {
        my $result = $validator->validate('Get API' => {
            status_code => 200,
            body => '200 OK',
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'Status 200 with invalid body' => sub {
        my $result = $validator->validate('Get API' => {
            status_code => 200,
            body => { status => 200, message => 'OK' },
        }, $schema);
        ok !$result->is_valid;
    };

    subtest 'Status 400 with valid body' => sub {
        my $result = $validator->validate('Get API' => {
            status_code => 400,
            body => encode_json({ status => 400, message => 'Bad Request' }),
        }, $schema);
        ok $result->is_valid;
    };

    subtest 'Status 400 with invalid body' => sub {
        my $result = $validator->validate('Get API' => {
            status_code => 400,
            body => '400 Bad Request',
        }, $schema);
        ok !$result->is_valid;
    };

    subtest 'Undefined status' => sub {
        my $result = $validator->validate('Get API' => {
            status_code => 599,
            body => { foo => 'bar' },
        }, $schema);
        ok $result->is_valid;
    };
}

t/Plack-App-APISchema-Document.t  view on Meta::CPAN

package t::Plack::App::APISchema::Document;
use lib '.';
use t::test;
use t::test::fixtures;
use t::test::InheritedDocument;
use Plack::Test;
use HTTP::Request::Common;

sub _require : Test(startup => 1) {
    my ($self) = @_;

    use_ok 'Plack::App::APISchema::Document';
}

sub instantiate : Tests {
    my $schema = APISchema::Schema->new;
    my $app = Plack::App::APISchema::Document->new(schema => $schema);

    isa_ok $app, 'Plack::App::APISchema::Document';
    is $app->schema, $schema;
}

sub serve_document : Tests {
     my $schema = t::test::fixtures::prepare_bmi;
     my $app = Plack::App::APISchema::Document->new(schema => $schema)->to_app;

     subtest 'when valid request' => sub {
         test_psgi $app => sub {
             my $server = shift;
             my $res = $server->(GET '/');
             is $res->code, 200;
             is $res->header('content-type'), 'text/html; charset=utf-8';
             like $res->content, qr{<h3 id="toc_8"><a name="resource-figure"></a> <code>figure</code> : <code>object</code></h3>};
             done_testing;
         }
     };
}

sub mojibake : Tests {
    my $schema = t::test::fixtures::prepare_author;
    my $app = Plack::App::APISchema::Document->new(schema => $schema)->to_app;

     subtest 'when valid request' => sub {
         test_psgi $app => sub {
             my $server = shift;
             my $res = $server->(GET '/');
             is $res->code, 200;
             is $res->header('content-type'), 'text/html; charset=utf-8';
             like $res->content, qr{td>著者</td>};
             done_testing;
         }
     };
}

sub inheritable : Tests {
    my $schema = t::test::fixtures::prepare_bmi;
    my $app = t::test::InheritedDocument->new(schema => $schema)->to_app;

    subtest 'Document is inheritable' => sub {
        test_psgi $app => sub {
            my $server = shift;
            my $res = $server->(GET '/');
            is $res->code, 200;
            is $res->header('content-type'), 'text/html; charset=utf-8';
            like $res->content, qr{pink};
            done_testing;
        };
    };
}



( run in 1.546 second using v1.01-cache-2.11-cpan-49f99fa48dc )