Coder Social home page Coder Social logo

openapi-data-mocker's Introduction

Openapi Data Mocker

Latest Stable Version Build Status Coverage Status License

Openapi Data Mocker helps to generate fake data from OpenAPI 3.0 documents. Most of the methods may work with 2.0 version(fka Swagger 2.0), but it's not tested. This package was an enhancement of PHP Slim4 server in OpenAPI Generator project, but it easier to maintain it in separated repo.

Requirements

  • PHP ^7.3

Important notice! While PHP 8.0 declared in composer.json this package hasn't been tested against it.

Installation via Composer

Run in terminal:

composer require ybelenko/openapi-data-mocker

Usage example

Imagine we have OpenAPI Specification 3.0.3 - Schema Object like this:

description: Real world example schema
type: object
properties:
  id:
    type: integer
    format: int32
    minimum: 1
  purchased_items:
    type: array
    items:
      type: object
      properties:
        SKU:
          type: string
          format: uuid
          maxLength: 20
        quantity:
          type: integer
          format: int32
          minimum: 1
          maximum: 5
        price:
          type: object
          properties:
            currency:
              type: string
              minLength: 3
              maxLength: 3
              enum:
              - USD
              - EUR
              - RUB
            value:
              type: number
              format: float
              minimum: 0.01
              maximum: 99.99
        manufacturer:
          type: object
          properties:
            name:
              type: string
              maxLength: 30
            country:
              type: string
              enum:
              - CHN
              - USA
              - RUS
  buyer:
    type: object
    properties:
      first_name:
        type: string
        minLength: 3
        maxLength: 15
      last_name:
        type: string
        minLength: 3
        maxLength: 15
      credit_card:
        type: integer
        minimum: 1000000000000000
        maximum: 10000000000000000
      phone:
        type: integer
        minimum: 10000000000000
        maximum: 99999999999999
      email:
        type: string
        format: email
  status:
    type: string
    enum:
    - registered
    - paid
    - shipped
    - delivered
    default: registered
  created_at:
    type: string
    format: date-time

Notice! While schema object presented in YAML format this library doesn't support YAML or JSON parsing right now. It means that mockSchemaObject method expects already decoded JSON value as argument.

When we mock mentioned schema with mockSchemaObject method:

require __DIR__ . '/vendor/autoload.php';

use OpenAPIServer\Mock\OpenApiDataMocker as Mocker;
$mocker = new Mocker();
// set model classes namespace for $ref handling
// current example doesn't use $refs in schemas, however
$mocker->setModelsNamespace('JohnDoesPackage\\Model\\');
// class InvoiceTest contains schema mentioned previously
// it returns that schema with getOpenApiSchema() method declared in OpenAPIServer\Mock\BaseModel parent class
$schema = \OpenAPIServer\Mock\Model\InvoiceTest::getOpenApiSchema();
$data = $mocker->mockSchemaObject($schema);
echo json_encode($data, \JSON_PRETTY_PRINT);

the output looks like:

{
    "id": 1912777939,
    "purchased_items": [
        {
            "SKU": "5ee78cfde9f05",
            "quantity": 4,
            "price": {
                "currency": "EUR",
                "value": 57.635
            },
            "manufacturer": {
                "name": "Lorem i",
                "country": "USA"
            }
        }
    ],
    "buyer": {
        "first_name": "Lorem ipsum do",
        "last_name": "Lorem ipsum ",
        "credit_card": 2455087473915908,
        "phone": 65526260517693,
        "email": "[email protected]"
    },
    "status": "delivered",
    "created_at": "1978-08-08T04:03:09+00:00"
}

Of course that output will be slightly different on every call. That's what mocker package has been developed for.

You can check extended example at examples/extended_example.php.

Supported features

All data types supported except specific string formats: email, uuid, password which are poorly implemented.

Data Types Support

Data Type Data Format Supported
integer int32
integer int64
number float
number double
string byte
string binary
boolean
string date
string date-time
string password
string email
string uuid

Data Options Support

Data Type Option Supported
string minLength
string maxLength
string enum
string pattern
integer minimum
integer maximum
integer exclusiveMinimum
integer exclusiveMaximum
number minimum
number maximum
number exclusiveMinimum
number exclusiveMaximum
array items
array additionalItems
array minItems
array maxItems
array uniqueItems
object properties
object maxProperties
object minProperties
object patternProperties
object additionalProperties
object required
* $ref
* allOf
* anyOf
* oneOf
* not

Known Limitations

Avoid circular refs in your schema. Schema below can cause infinite loop and Out of Memory PHP error:

# ModelA has reference to ModelB while ModelB has reference to ModelA.
# Mock server will produce huge nested JSON example and ended with `Out of Memory` error.
definitions:
  ModelA:
    type: object
    properties:
      model_b:
        $ref: '#/definitions/ModelB'
  ModelB:
    type: array
    items:
      $ref: '#/definitions/ModelA'

Don't ref scalar types, because generator will not produce models which mock server can find. So schema below will cause error:

# generated build contains only `OuterComposite` model class which referenced to not existed `OuterNumber`, `OuterString`, `OuterBoolean` classes
# mock server cannot mock `OuterComposite` model and throws exception
definitions:
  OuterComposite:
    type: object
    properties:
      my_number:
        $ref: '#/definitions/OuterNumber'
      my_string:
        $ref: '#/definitions/OuterString'
      my_boolean:
        $ref: '#/definitions/OuterBoolean'
  OuterNumber:
    type: number
  OuterString:
    type: string
  OuterBoolean:
    type: boolean

Links to mentioned technologies

openapi-data-mocker's People

Contributors

ybelenko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

openapi-data-mocker's Issues

Add fzaninotto/faker as optional mocking engine

It would be great to use fakerphp/faker as fake data provider because:

  1. It's well known stable solution with many features.
  2. It supports seed to generate the same values in unit tests.
  3. It generates real human examples in comparison to this package.
  4. It can generate data for different locales.

The only disadvantage of fzaninotto/faker is library size(3.5MB). That's why I'm going to add it as suggest package, not required.

I submit this issue just to show what I'm working on right now!

Add implementation of OpenApiServerMockerInterface

I'm creating first implementation of OpenAPIServer\Mock\OpenApiServerMockerInterface

This class is crucial for server unit tests.
For example, when I need to test createUser API operation I need to mock valid Psr\Http\Message\ServerRequestInterface instance based on OAS3.0 Path Item Object and pass it to server handler. That's what OpenAPIServer\Mock\OpenApiServerMockerInterface::mockRequest method has been created for:

    public function mockRequest(
        string $path,
        string $method,
        ?array $parameters = null,
        ?array $requestBody = null,
        ?array $security = null,
        ?array $callbacks = null
    ): ServerRequestInterface;

I submit this issue just to show what I'm working on right now!

Add method to provide complete OAS spec file

Package accepts deserialized parts of OAS spec as arguments right now. However, it might be much more convenient to specify path to complete OAS spec file and use only operation/model names to mock data.

As a conclusion, package should:

  1. Parse yaml or json OAS spec file and store result in static variable.
  2. Provide additional methods like:
    • mockModelFromSpec(string $modelName)
    • mockOperationFromSpec(string $operationId)
    • mockResponseFromSpec(string $operationId, string $responseStatusCode = 'default', string $mediaType = null).

I guess there might be issues with specs divided into many referenced files, but it's not common case and can be fixed afterwards.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.