starsz commented on a change in pull request #5940:
URL: https://github.com/apache/apisix/pull/5940#discussion_r792251381



##########
File path: docs/en/latest/plugins/mocking.md
##########
@@ -0,0 +1,236 @@
+---
+title: mocking
+---
+
+<!--
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+-->
+
+## Summary
+
+- [**Name**](#name)
+- [**Attributes**](#attributes)
+- [**How To Enable**](#how-to-enable)
+- [**Test Plugin**](#test-plugin)
+- [**Disable Plugin**](#disable-plugin)
+
+## Name
+
+Mock API plugin,Binding the plugin returns random mock data in the specified 
format and is no longer forwarded to the back end.
+
+## Attributes
+
+| Name            | Type    | Requirement | Default | Valid                    
                                        | Description                           
                                                                                
                                   |
+| -------------   | -------| ----- | ----- | 
-------------------------------------------------------------- | 
-------------------------------------------------------------------------------------------------------------------------------------------------
 |
+| delay           | integer | optional |        |                              
                                   | Delay return time, in seconds              
                              |
+| response_status | integer| optional  | 200 |                                 
                                | response http status code                     
                       |
+| content_type    | string | optional  | application/json |                    
                                             | response header Content-Type。    
                                        |
+| response_example| string | optional  |        |                              
                                   | response body                              
              |
+| response_schema | object | optional  |        |                              
                                   | The jSON-schema object for the response is 
specified. This property takes effect if the `response_example` is not 
specified                                            |
+| with_mock_header | boolean | optional | true  |                              
                                   | Whether to return the response header: 
"x-mock-by: APISIX/{version}", returned by default, false does not return       
 |
+
+Supported field types: `string`, `number`, `INTEGER`, `Boolean`, `object`, 
`array`

Review comment:
       Why `INTERGER` is upper case? And so do `Boolean` 

##########
File path: apisix/plugins/mocking.lua
##########
@@ -0,0 +1,207 @@
+--
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+--
+local core = require("apisix.core")
+local ngx = ngx
+local xml2lua = require("xml2lua")
+local string = string
+local type = type
+local table = table
+local math = math
+local pairs = pairs
+
+local schema = {
+    type = "object",
+    properties = {
+        -- specify response delay time,default 0ms
+        delay = { type = "integer", default = 0 },
+        -- specify response status,default 200
+        response_status = { type = "integer", default = 200, minimum = 100 },
+        -- specify response content type, support application/xml, text/plain
+        -- and application/json, default application/json
+        content_type = { type = "string", default = 
"application/json;charset=utf8" },
+        -- specify response body.
+        response_example = { type = "string" },
+        -- specify response json schema, if response_example is not nil, this 
conf will be ignore.
+        -- generate random response by json schema.
+        response_schema = { type = "object" },
+        with_mock_header = { type = "boolean", default = true }
+    },
+    anyOf = {
+        { required = { "response_example" } },
+        { required = { "response_schema" } }
+    }
+}
+
+local _M = {
+    version = 0.1,
+    priority = 9900,
+    name = "mocking",
+    schema = schema,
+}
+
+local function parse_content_type(content_type)
+    if not content_type then
+        return ""
+    end
+    local m = ngx.re.match(content_type, "([ -~]*);([ -~]*)")
+    if #m == 2 then
+        return m[1], m[2]
+    end
+    return content_type
+end
+
+function _M.check_schema(conf)
+    local ok, err = core.schema.check(schema, conf)
+    if not ok then
+        return false, err
+    end
+
+    local typ = parse_content_type(conf.content_type)
+    local support_content_type = {
+        ["application/xml"] = true,
+        ["application/json"] = true,
+        ["text/plain"] = true,
+        ["text/html"] = true,
+        ["text/xml"] = true
+    }
+    if not support_content_type[typ] then
+        return false, "unsupported content type!"
+    end
+    return true
+end
+
+local function gen_string(example)
+    if example and type(example) == "string" then
+        return example
+    end
+    local n = math.random(1, 10)
+    local list = {}
+    for i = 1, n do
+        table.insert(list, string.char(math.random(97, 122)))
+    end
+    return table.concat(list)
+end
+
+local function gen_number(example)
+    if example and type(example) == "number" then
+        return example
+    end
+    return math.random() * 10000
+end
+
+local function gen_integer(example)
+    if example and type(example) == "number" then
+        return math.floor(example)
+    end
+    return math.random(1, 10000)
+end
+
+local function gen_boolean(example)
+    if example and type(example) == "boolean" then
+        return example
+    end
+    local r = math.random(0, 1)
+    if r == 0 then
+        return false
+    end
+    return true
+end
+
+local function gen_base(property)
+    local typ = string.lower(property.type)
+    local example = property.example
+    if typ == "string" then
+        return gen_string(example)
+    elseif typ == "number" then
+        return gen_number(example)
+    elseif typ == "integer" then
+        return gen_integer(example)
+    elseif typ == "boolean" then
+        return gen_boolean(example)
+    end
+    return nil
+end
+
+
+local gen_array, gen_object
+
+function gen_array(property)
+    local output = {}
+    if property.items == nil then
+        return nil
+    end
+    local v = property.items
+    local n = math.random(1, 3)
+    local typ = string.lower(v.type)
+    for i = 1, n do
+        if typ == "array" then
+            table.insert(output, gen_array(v))
+        elseif typ == "object" then
+            table.insert(output, gen_object(v))
+        else
+            table.insert(output, gen_base(v))
+        end
+    end
+    return output
+end
+
+function gen_object(property)
+    local output = {}
+    if not property.properties then
+        return output
+    end
+    for k, v in pairs(property.properties) do
+        local typ = string.lower(v.type)
+        if typ == "array" then
+            output[k] = gen_array(v)
+        elseif typ == "object" then
+            output[k] = gen_object(v)
+        else
+            output[k] = gen_base(v)
+        end
+    end
+    return output
+end
+
+function _M.access(conf)
+    local response_content = ""
+
+    if conf.response_example then
+        response_content = conf.response_example
+    else
+        local output = gen_object(conf.response_schema)
+        local typ, _ = parse_content_type(conf.content_type)

Review comment:
       ```suggestion
           local typ = parse_content_type(conf.content_type)
   ```

##########
File path: docs/en/latest/plugins/mocking.md
##########
@@ -0,0 +1,236 @@
+---
+title: mocking
+---
+
+<!--
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+-->
+
+## Summary
+
+- [**Name**](#name)
+- [**Attributes**](#attributes)
+- [**How To Enable**](#how-to-enable)
+- [**Test Plugin**](#test-plugin)
+- [**Disable Plugin**](#disable-plugin)
+
+## Name
+
+Mock API plugin,Binding the plugin returns random mock data in the specified 
format and is no longer forwarded to the back end.
+
+## Attributes
+
+| Name            | Type    | Requirement | Default | Valid                    
                                        | Description                           
                                                                                
                                   |
+| -------------   | -------| ----- | ----- | 
-------------------------------------------------------------- | 
-------------------------------------------------------------------------------------------------------------------------------------------------
 |
+| delay           | integer | optional |        |                              
                                   | Delay return time, in seconds              
                              |
+| response_status | integer| optional  | 200 |                                 
                                | response http status code                     
                       |
+| content_type    | string | optional  | application/json |                    
                                             | response header Content-Type。    
                                        |
+| response_example| string | optional  |        |                              
                                   | response body                              
              |
+| response_schema | object | optional  |        |                              
                                   | The jSON-schema object for the response is 
specified. This property takes effect if the `response_example` is not 
specified                                            |
+| with_mock_header | boolean | optional | true  |                              
                                   | Whether to return the response header: 
"x-mock-by: APISIX/{version}", returned by default, false does not return       
 |
+
+Supported field types: `string`, `number`, `INTEGER`, `Boolean`, `object`, 
`array`
+Base data types (string, number, integer, Boolean) through configuration 
example attribute to specify the generated response value, random return not 
configured.
+Here is a JSON-Schema example:
+
+```json
+{
+    "properties":{
+        "field0":{
+            "example":"abcd",
+            "type":"string"
+        },
+        "field1":{
+            "example":123.12,
+            "type":"number"
+        },
+        "field3":{
+            "properties":{
+                "field3_1":{
+                    "type":"string"
+                },
+                "field3_2":{
+                    "properties":{
+                        "field3_2_1":{
+                            "example":true,
+                            "type":"boolean"
+                        },
+                        "field3_2_2":{
+                            "items":{
+                                "example":155.55,
+                                "type":"integer"
+                            },
+                            "type":"array"
+                        }
+                    },
+                    "type":"object"
+                }
+            },
+            "type":"object"
+        },
+        "field2":{
+            "items":{
+                "type":"string"
+            },
+            "type":"array"
+        }
+    },
+    "type":"object"
+}
+```
+
+Here are the return objects that might be generated by this JSON-Schema:
+
+```json
+{
+    "field1": 123.12,
+    "field3": {
+        "field3_1": "LCFE0",
+        "field3_2": {
+            "field3_2_1": true,
+            "field3_2_2": [
+                155,
+                155
+            ]
+        }
+    },
+    "field0": "abcd",
+    "field2": [
+        "sC"
+    ]
+}
+```
+
+## 如何启用

Review comment:
       Avoid using Chinese in English doc.

##########
File path: t/plugin/mocking.t
##########
@@ -0,0 +1,136 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+BEGIN {
+    if ($ENV{TEST_NGINX_CHECK_LEAK}) {
+        $SkipReason = "unavailable for the hup tests";
+
+    } else {
+        $ENV{TEST_NGINX_USE_HUP} = 1;
+        undef $ENV{TEST_NGINX_USE_STAP};
+    }
+}
+
+use t::APISIX 'no_plan';
+
+repeat_each(1);
+no_long_string();
+no_shuffle();
+no_root_location();
+log_level('info');
+run_tests;
+
+__DATA__
+
+=== TEST 1: set route(return response example:"hello world")
+--- config
+       location /t {
+           content_by_lua_block {
+               local t = require("lib.test_admin").test
+               local code, body = t('/apisix/admin/routes/1',
+                    ngx.HTTP_PUT,
+                    [[{
+                           "plugins": {
+                               "mocking": {
+                                   "delay": 1,
+                                   "content_type": "text/plain",
+                                   "response_status": 200,
+                                   "response_example": "hello world"
+                               }
+                           },
+                           "uri": "/hello"
+                   }]]
+                   )
+
+               if code >= 300 then
+                   ngx.status = code
+               end
+               ngx.say(body)
+           }
+       }
+--- request
+GET /t
+--- error_code: 200
+--- response_body
+passed
+--- no_error_log
+[error]
+
+
+
+=== TEST 2: hit route(return response example:"hello world")
+--- request
+GET /hello
+--- error_code: 200
+--- response_body chomp
+hello world
+--- no_error_log
+[error]
+
+
+
+=== TEST 3: set route(return response schema)
+--- config
+       location /t {
+           content_by_lua_block {
+               local t = require("lib.test_admin").test
+               local code, body = t('/apisix/admin/routes/1',
+                    ngx.HTTP_PUT,
+                    [[{
+                           "plugins": {
+                               "mocking": {
+                                   "delay": 1,
+                                   "content_type": "text/plain",
+                                   "response_status": 200,
+                                   "response_schema": {
+                                       "type": "object",
+                                       "properties": {
+                                           "field1":{
+                                               "type":"string",
+                                               "example":"hello"
+                                           }
+                                       }
+                                   }
+                               }
+                           },
+                           "uri": "/hello"
+                   }]]
+                   )
+
+               if code >= 300 then
+                   ngx.status = code
+               end
+               ngx.say(body)
+           }
+       }
+--- request
+GET /t
+--- error_code: 200
+--- response_body
+passed
+--- no_error_log
+[error]
+
+
+
+=== TEST 4: hit route(return response schema)
+--- request
+GET /hello
+--- error_code: 200
+--- response_body chomp
+{"field1":"hello"}
+--- no_error_log
+[error]

Review comment:
       Better to add a test for `string`, `number`, `integer`, `boolean`.

##########
File path: apisix/plugins/mocking.lua
##########
@@ -0,0 +1,207 @@
+--
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+--
+local core = require("apisix.core")
+local ngx = ngx
+local xml2lua = require("xml2lua")
+local string = string
+local type = type
+local table = table
+local math = math
+local pairs = pairs
+
+local schema = {
+    type = "object",
+    properties = {
+        -- specify response delay time,default 0ms
+        delay = { type = "integer", default = 0 },
+        -- specify response status,default 200
+        response_status = { type = "integer", default = 200, minimum = 100 },
+        -- specify response content type, support application/xml, text/plain
+        -- and application/json, default application/json
+        content_type = { type = "string", default = 
"application/json;charset=utf8" },
+        -- specify response body.
+        response_example = { type = "string" },
+        -- specify response json schema, if response_example is not nil, this 
conf will be ignore.
+        -- generate random response by json schema.
+        response_schema = { type = "object" },
+        with_mock_header = { type = "boolean", default = true }
+    },
+    anyOf = {
+        { required = { "response_example" } },
+        { required = { "response_schema" } }
+    }
+}
+
+local _M = {
+    version = 0.1,
+    priority = 9900,
+    name = "mocking",
+    schema = schema,
+}
+
+local function parse_content_type(content_type)
+    if not content_type then
+        return ""
+    end
+    local m = ngx.re.match(content_type, "([ -~]*);([ -~]*)")

Review comment:
       Better to define `local ngx_re = ngx.re` in the front




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to