问题
I have one example where i was not able to achieve my problem with Karate. I have 25 ecg files where I should upload them to a patient. There's an index file which contains the right order of those files. But before uploading via API, I need read that index file, find the next file to upload.
Also i need to rename those file with a specific naming convention cause every file i upload via api should.be unique. The name consist of patient email, a timestamp and an index. Also timestamp in the name should be increased for each file with 25500ms. After the upload, i should delete those files.
I tried to write a java interop,etc but then it became so complicated.
回答1:
This is actually quite simple using Karate. First I assume you have an index.json
with the following:
[
{ "file": "ecg-01.json" },
{ "file": "ecg-02.json" }
]
The contents of ecg-01.json
:
{ "email": "john@ecg.com" }
And contents of ecg-02.json
:
{ "email": "smith@ecg.com" }
Note that in Karate you don't need to save temporary files for file-upload, you can take an existing file and perform an upload with a different name, refer: https://github.com/intuit/karate#multipart-file
We will do the main work in upload.feature
, here we just use https://httpbin.org/
as a demo endpoint:
Scenario:
* def patient = read(file)
* def timeStamp = startTime + __loop * 25500
* def name = patient.email + '_' + timeStamp + '_' + __loop
* url 'https://httpbin.org/anything'
* request { name: '#(name)' }
* method post
So finally all you need to do is a loop from your main feature, which can be as simple as this:
* def startTime = java.lang.System.currentTimeMillis()
* def data = read('index.json')
* call read('upload.feature') data
When I ran this example, it made 2 POST requests like this:
1 > POST https://httpbin.org/anything
1 > Accept-Encoding: gzip,deflate
1 > Connection: Keep-Alive
1 > Content-Length: 39
1 > Content-Type: application/json; charset=UTF-8
1 > Host: httpbin.org
1 > User-Agent: Apache-HttpClient/4.5.11 (Java/1.8.0_231)
{"name":"john@ecg.com_1582424404163_0"}
1 > POST https://httpbin.org/anything
1 > Accept-Encoding: gzip,deflate
1 > Connection: Keep-Alive
1 > Content-Length: 40
1 > Content-Type: application/json; charset=UTF-8
1 > Host: httpbin.org
1 > User-Agent: Apache-HttpClient/4.5.11 (Java/1.8.0_231)
{"name":"smith@ecg.com_1582424429663_1"}
That said, suppose you wanted to write the file creation logic as pure Java. You could have then passed it to Karate in one line, and deleted it in another line. No, Java interop in Karate is not "so complicated".
来源:https://stackoverflow.com/questions/60358696/complex-data-driven-test-reading-multiple-files