2017-10-10 144 views
1

我想通過json模式檢查GET/birds請求的響應。在我的功能:如何使用if條件檢查附加值(使用空手道框架)?

* def abs = read (birds.json) 
* match response == abs.birdsSchema 

我需要把架構在json文件中,而不是在功能。 我必須根據性別檢查其他值。例如:如果性別是男性,那麼檢查顏色是藍色還是尾巴長或短。如果性別是女性,那麼檢查「唱歌」是真是假,雞蛋數量。

所以我把在birds.json:

"birdsSchema":{ 
    "id": "#string", 
    "owner": "#number", 
    "town": "#? _ == 'New York' || _ == 'Washington'", 
    "type": "object", 
    "oneOf": [ 
     { 
      "properties": { 
       "gender": {"enum": ["male"]}, 
       "color":"blue", 
       "tail": "#? _ == 'long' || _ == 'short'" 
      } 
     }, 
     { 
      "properties": { 
       "gender": {"enum": ["female"]}, 
       "sings" : "#? _ == true || _ == false" 
       "eggs": "##number" 
      } 
     } 
    ] 
} 

但它不工作。錯誤:com.intuit.karate.exception.KarateException:path:$ [0] .type,actual:'female',expected:'object',reason:not equal。 如何在我的json文件中做這個條件檢查?

回答

1

讓我們承認,這是非常困難的,因爲如果我正確理解你的問題,你正在尋找的JSON 是動態的。

空手道的一部分樂趣是,至少有5種不同的方式可以讓我想到優雅地解決這個問題。這裏只是一個:

* def response = { color: 'black', aaa: 'foo' } 

* def schema = { color: '#? _ == "black" || _ == "white"' } 
* def extra = (response.color == 'black' ? { aaa: '#string' } : { fff: '#string' }) 

* match response contains schema 
* match response contains extra 

如果你基於上面的提示創建一個JS函數,你可能會得到一個更好的解決方案。請記住,在JS函數中,您可以使用諸如karate.set之類的方法動態創建密鑰。所以有很多的可能性:)

編輯:看起來像上面的例子是錯誤的,關鍵是不是動態。那麼很容易,記住,$指JSON根:

* def response = { color: 'black', extra: 'foo' }  
* def schema = { color: '#? _ == "black" || _ == "white"', extra: '#($.color == "black" ? "foo" : "bar")' }  
* match response == schema 
+0

感謝您所有的快速回復。我知道如何在功能上做到這一點,感謝空手道官方tuto,但我想在一個json文件中做到這一點。這個想法是,將只有一個json文件的輪子模式,不同的功能將使用它作爲響應驗證。我如何在json文件中做同樣的事情? – nirind

+0

JSON密鑰不是動態的 – nirind

+0

確定請參閱我的編輯:\ –

相關問題