【问题标题】:Karate: How to test multipart form-data endpoint? [duplicate]空手道:如何测试多部分表单数据端点? [复制]
【发布时间】:2019-04-11 20:27:38
【问题描述】:

我在控制器中有一个文件上传端点(/document),定义如下:

@RestController
public class FileUploadController {

    @Autowired
    private PersonCSVReaderService personCSVReaderService;

    @PostMapping(value = "/document", consumes= {MediaType.MULTIPART_FORM_DATA_VALUE})
    public void handleFileUpload3(@RequestPart("file") MultipartFile file, @RequestPart("metadata") DocumentMetadata metadata) {
        System.out.println(String.format("uploading file %s of %s bytes", file.getOriginalFilename(), file.getSize()));
        personCSVReaderService.readPersonCSV(file, metadata);
    }
}

我可以使用 Advanced Rest Client (ARC) 或 Postman 测试此端点,方法是定义引用 people.csv 文件的“文件”部分和指定一些示例元数据 JSON 的文本部分。

一切正常,我得到了 200 状态,其中 people.csv 文件内容通过服务方法写入控制台输出:

uploading file people.csv of 256 bytes
{Address=1, City=2, Date of Birth=6, Name=0, Phone Number=5, State=3, Zipcode=4}
Person{name='John Brown', address='123 Main St.', city='Scottsdale', state='AZ', zipcode='85259', phoneNumber='555-1212', dateOfBirth='1965-01-01'}
Person{name='Jan Black', address='456 University Dr.', city='Atlanta', state='GA', zipcode='30306', phoneNumber='800-1111', dateOfBirth='1971-02-02'}
Person{name='Mary White', address='789 Possum Rd.', city='Nashville', state='TN', zipcode='37204', phoneNumber='888-2222', dateOfBirth='1980-03-03'}

现在,我想将其作为自动化空手道测试运行。我已经指定了一个 MockConfig :

@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
public class MockConfig {

    // Services ...
    @Bean
    public PersonCSVReaderService personCSVReaderService() {
        return new PersonCSVReaderService();
    }

    // Controllers ...
    @Bean
    public FileUploadController fileUploadController() {
        return new FileUploadController();
    }
}

我在类路径中也有一个 MockSpringMvcServlet,我的 karate-config.js 是:

function fn() {    
   var env = karate.env; // get system property 'karate.env'
   if (!env) {
      env = 'dev';
   }
   karate.log('karate.env system property was:', env);

   var config = {
     env: env,
     myVarName: 'someValue',
     baseUrl: 'http://localhost:8080'
   }

   if (env == 'dev') {
      var Factory = Java.type('MockSpringMvcServlet');
      karate.configure('httpClientInstance', Factory.getMock());
      //var result = karate.callSingle('classpath:demo/headers/common-noheaders.feature', config);
   } else if (env == 'stg') {
      // customize
   } else if (env == 'prod') {
      // customize
   }

   return config;
}

其他空手道测试使用模拟 servlet 运行正常。

但是,当我尝试这个测试来测试 /document 端点时:

Feature: file upload end-point

  Background:
    * url baseUrl
    * configure lowerCaseResponseHeaders = true

  Scenario: upload file
    Given path '/document'
    And header Content-Type = 'multipart/form-data'
    And multipart file file =  { read: 'people.csv', filename: 'people.csv', contentType: 'text/csv' }
    And multipart field metadata = { name: "joe", description: "stuff" }
    When method post
    Then status 200

我收到此错误:

16:14:42.674 [main] INFO  com.intuit.karate - karate.env system property was: dev 
16:14:42.718 [main] INFO  o.s.mock.web.MockServletContext - Initializing Spring DispatcherServlet ''
16:14:42.719 [main] INFO  o.s.web.servlet.DispatcherServlet - Initializing Servlet ''
16:14:43.668 [main] INFO  o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$a4c7d08f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
16:14:43.910 [main] INFO  o.h.validator.internal.util.Version - HV000001: Hibernate Validator 6.0.14.Final
16:14:44.483 [main] INFO  o.s.s.c.ThreadPoolTaskExecutor - Initializing ExecutorService 'applicationTaskExecutor'
16:14:44.968 [main] INFO  o.s.b.a.e.web.EndpointLinksResolver - Exposing 2 endpoint(s) beneath base path '/actuator'
16:14:45.006 [main] INFO  o.s.web.servlet.DispatcherServlet - Completed initialization in 2287 ms
16:14:45.066 [main] INFO  c.i.k.mock.servlet.MockHttpClient - making mock http client request: POST - http://localhost:8080/document
16:14:45.085 [main] DEBUG c.i.k.mock.servlet.MockHttpClient - 
1 > POST http://localhost:8080/document
1 > Content-Type: multipart/form-data

16:14:45.095 [main] ERROR com.intuit.karate - http request failed: null
file-upload.feature:13 - null
HTML report: (paste into browser to view) | Karate version: 0.9.2

我只能假设参数不符合我的端点所期望的 - 我从未在调试模式下进入端点。

我试过这个:

    And multipart file file =  read('people.csv')
    And multipart field metadata = { name: "joe", description: "stuff" }

但这也不是首发。

我做错了什么? people.csv 与 fileupload.feature 位于同一文件夹中,因此我假设它正在查找文件。我还查看了此处给出的空手道演示项目中的 upload.feature 文件:

Karate demo project upload.feature

但我无法让它工作。任何帮助表示赞赏。提前致谢。

邮递员请求如下所示:

编辑更新:

我无法得到建议的答案。

这里是功能文件:

Feature: file upload

  Background:
    * url baseUrl
    * configure lowerCaseResponseHeaders = true

  Scenario: upload file
    Given path '/document'
    And header Content-Type = 'multipart/form-data'
    * def temp = karate.readAsString('people.csv')
    * print temp
    And multipart file file =  { value: '#(temp)', filename: 'people.csv', contentType: 'text/csv' }
    And multipart field metadata = { value: {name: 'joe', description: 'stuff'}, contentType: 'application/json' }
    When method post
    Then status 200

这是运行该测试的控制台输出:

09:27:22.051 [main] INFO  com.intuit.karate - found scenario at line: 7 - ^upload file$
09:27:22.156 [main] INFO  com.intuit.karate - karate.env system property was: dev 
09:27:22.190 [main] INFO  o.s.mock.web.MockServletContext - Initializing Spring DispatcherServlet ''
09:27:22.190 [main] INFO  o.s.web.servlet.DispatcherServlet - Initializing Servlet ''
09:27:23.084 [main] INFO  o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$a4c7d08f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
09:27:23.327 [main] INFO  o.h.validator.internal.util.Version - HV000001: Hibernate Validator 6.0.14.Final
09:27:23.896 [main] INFO  o.s.s.c.ThreadPoolTaskExecutor - Initializing ExecutorService 'applicationTaskExecutor'
09:27:24.381 [main] INFO  o.s.b.a.e.web.EndpointLinksResolver - Exposing 2 endpoint(s) beneath base path '/actuator'
09:27:24.418 [main] INFO  o.s.web.servlet.DispatcherServlet - Completed initialization in 2228 ms
09:27:24.435 [main] INFO  com.intuit.karate - [print] Name,Address,City,State,Zipcode,Phone Number,Date of Birth
John Brown,123 Main St.,Scottsdale,AZ,85259,555-1212,1965-01-01
Jan Black,456 University Dr.,Atlanta,GA,30306,800-1111,1971-02-02
Mary White,789 Possum Rd.,Nashville,TN,37204,888-2222,1980-03-03

09:27:24.482 [main] INFO  c.i.k.mock.servlet.MockHttpClient - making mock http client request: POST - http://localhost:8080/document
09:27:24.500 [main] DEBUG c.i.k.mock.servlet.MockHttpClient - 
1 > POST http://localhost:8080/document
1 > Content-Type: multipart/form-data

09:27:24.510 [main] ERROR com.intuit.karate - http request failed: null
file-upload.feature:14 - null
HTML report: (paste into browser to view) | Karate version: 0.9.2

注意:people.csv 文件读取成功并在控制台打印。

【问题讨论】:

    标签: karate


    【解决方案1】:

    参考这部分文档:https://github.com/intuit/karate#read-file-as-string

    所以做出这个改变:

    * def temp = karate.readAsString('people.csv')
    And multipart file file =  { value: '#(temp)', filename: 'people.csv', contentType: 'text/csv' }
    

    编辑:我的错,另请参阅:https://github.com/intuit/karate#multipart-file

    【讨论】:

    • 上面会导致错误,因为它试图使用 people.csv 文件的全部内容作为文件名。
    • @joe 道歉,我的错 - 请参阅我的编辑。请阅读文档 - 它解释了所有这些事情
    • 是的,我事先阅读了文档。我尝试了一堆变体,但无法让它们中的任何一个工作,我求助于堆栈溢出来寻求帮助。在 ARC 或 Postman 中,我可以通过将文件部分指定为我的文件 people.csv 和通过设置 content-type 并将 JSON 作为元数据提供如上所述的文本部分来使请求正常工作。我很抱歉你没有掌握如何完成这项工作。
    • 仍然失败。也许我的模拟设置有问题。
    • 彼得,我无法让您的建议生效。我用结果编辑了上面的问题。
    【解决方案2】:

    功能:上传 csv

    背景:and def admin = read('classpath:com/project/data/adminLogin.json')

    场景: 给定 url baseUrl

    并且标头Authorization = admin.token

    和多部分文件 residentDetails = { read:'classpath:com/project/data/ResidentApp_Details.csv', filename: 'ResidentApp_Details.csv' }

    当方法 POST 时

    然后状态 200

    注意:只多加一行,即多部分文件 residentDetails = { read:'classpath:com/project/data/residentApp_Details.csv', filename: 'residentApp_Details.csv' }

    【讨论】:

    • 我不明白你的建议。你能补充更多解释吗?
    • 当您想在 Api 请求正文中添加任何 csv 或其他文件时,您只需在代码中添加以下行:。而多部分文件 residentDetails = { read:'classpath:com/project/data/ResidentApp_Details.csv', filename: 'residentApp_Details.csv' }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多