POSTMAN -即使响应数据不正确,模式验证也会通过

hsgswve4  于 2022-11-07  发布在  Postman
关注(0)|答案(3)|浏览(209)

验证数据的有效性;即使架构中缺少“error”和“responseType”,也会传递。如何确保响应和架构都与JSON架构匹配。
当我点击postman上的post请求时,下面是postman中的响应正文

{  
  "statusCode": 400,
  "error": "Bad Request",
  "message": "Email/Phone number not found",
  "responseType": "EMAIL_NOT_FOUND",
  "arabicMessage": "البريد الإلكتروني / رقم الهاتف غير موجود"
  }

Postman 测试

var jsonData=JSON.parse(responseBody)
var schema ={
    "statusCode": {"type":"integer"},
    "message": {"type":"string"},
    "arabicMessage":{"type":"string"},
    "data": {
        "accessToken": {"type":"string"},
        "userDetails": {
            "_id": {"type":"string"},
            "deviceType": {"type":"string"},
            "countryCode": {"type":"string"},
            "OTPCode": {"type":"integer"},
            "invitationCode": {"type":"string"},
            "availableCredits": {"type":"integer"},
            "totalBookings": {"type":"integer"},
            "promoCodes": {"type":"array"},
            "updatedAt": {"type":"string"},
            "createdAt": {"type":"string"},
            "language": {"type":"string"},
            "IsDeleted": {"type":"boolean"},
            "IsVerified": {"type":"boolean"},
            "IsBlock": {"type":"boolean"},
            "customerAddresses": {"type":"array"},
            "address":{"type":"string"},
            "phoneVerified": {"type":"boolean"},
            "currentLocation": {
                "type": "Point",
                "coordinates": [
                   {"type":"integer"},
                   {"type":"integer"}
                ]
            },
            "appVersion": {"type":"integer"},
            "profilePicURL": {
                "thumbnail": {"type":"string"},
                "original": {"type":"string"}
            },
            "password":  {"type":"string"},
            "socialId": {"type":"string"},
            "phoneNo": {"type":"integer"},
            "email": {"type":"string"},
            "LastName": {"type":"string"},
            "firstName": {"type":"string"},
            "__v": {"type":"integer"},
            "referralCode":  {"type":"string"},
            "accessToken": {"type":"string"},
            "deviceToken":  {"type":"string"}
        },
        "updateAvailable": {"type":"boolean"},
        "stateCallBookingIds":  {"type":"array"},
        "forceUpdate": {"type":"boolean"}
    }
 };
tests["Valid schema"] = tv4.validate(jsonData, schema);
//here the test is passing even with invalid jsonData which is the data                       
 console.log("Validation failed: ", tv4.error);
eqfvzcg8

eqfvzcg81#

关于tv4模块, Postman github账户上有很多open issues
在SO here上也有一个类似的问题,jsonData是否与模式不同?
这是一个example从tv4 github页面上的一个链接。

"title": "Person",
"type": "object",
"properties": {
    "firstName": {
        "type": "string"
    },
    "lastName": {
        "type": "string"
    },
    "age": {
        "description": "Age in years",
        "type": "integer",
        "minimum": 0
    }
},
"required": ["firstName", "lastName"]
}

您可以尝试将这些字段添加为required

ndh0cuux

ndh0cuux2#

这里只留下它,以防它对其他人有帮助。tv4.validate有两个附加的布尔参数:checkRecursivebanUnkownProperties中的一个或多个。
特别是最后一个,当JSON响应包含模式中未定义的属性时,它可以帮助查找JSON响应中的错误。
参考文献

h22fl7wq

h22fl7wq3#

我更喜欢这样使用jsonSchema:

var strSchema = 
pm.collectionVariables.get("variable_that_contains_the_schema");

pm.test("Validate SCHEMA is OK", () => {
    pm.response.to.have.jsonSchema(JSON.parse(strSchema));
});

如果您想自动生成模式,可以使用generate-schema插件https://www.npmjs.com/package/generate-schema
我使用来存储这个插件的内容在一个集合变量中,在我的集合的预先请求,像这样:

然后在请求的测试标签中,可以调用javascript eval()在 Postman 的测试环境中加载generate-schema源代码:

// eval will evaluate the JavaScript generateSchema code and 
// initialize the js on postman environment
eval(pm.collectionVariables.get("generate-schema"));

var strSchema = 
pm.collectionVariables.get("variable_that_contains_the_schema");

if (strSchema === undefined){
  console.log('>>>> variable for schema not defined!');
  return;  
}
if(strSchema == '' | strSchema === null) {
    // call function generateSchema (external)
    var schema = generateSchema.json("variable_that_contains_the_schema", jsonData);

    delete schema.$schema; // remove the element '$schema' --> causes error in validator
    var strSchema = JSON.stringify(schema);

    //save the generated schema
    pm.collectionVariables.set("variable_that_contains_the_schema", strSchema);
    console.log(" >> schema was generated from the response, validation will proceed on the next request.");
}
else
{
    console.log(" >> schema recovered from variable.");

    // Schema test ------------------------------------------------
    pm.test("Validate SCHEMA is OK", () => {
        pm.response.to.have.jsonSchema(JSON.parse(strSchema));
    });
}

相关问题