Как можно загрузить PDF-файл с помощью Karate UI Automation? - PullRequest
1 голос
/ 23 апреля 2020

Связанные с этим проблемы: Можно ли загружать / скачивать файлы в Драйвере для каратэ? , Не могли бы вы помочь мне создать код пользовательского интерфейса каратэ для загрузки в формате pdf в формате Excel:

<div class="col-sm-6">
                    <div class="form-group shiny-input-container">
                      <label>Faça o upload do seu arquivo</label>
                      <div class="input-group">
                        <label class="input-group-btn">
                          <span class="btn btn-default btn-file">
                            Browse...
                            <input id="file_input" name="file_input" type="file" style="display: none;" data-shinyjs-resettable-id="file_input" data-shinyjs-resettable-type="File" data-shinyjs-resettable-value="" class="shinyjs-resettable shiny-bound-input">
                          </span>
                        </label>
                        <input type="text" class="form-control" placeholder="No file selected" readonly="readonly">
                      </div>
                      <div id="file_input_progress" class="progress progress-striped active shiny-file-input-progress">
                        <div class="progress-bar"></div>
                      </div>
                    </div>
                  </div>

Я попытался использовать этот исходный код ниже безуспешно:

* def uri = 'http://the-internet.herokuapp.com/upload'
    * def uploadSelector = '#file-upload'
    * def submitSelector = '#file-submit'

    # this function is for getting the full path of a file that is necessary to use with selenium sendKeys method when
    # a file. I agree with the fact that every folder in Karate would contain the files used within the feature. Nevertheless
    # having it results in a duplication of files if a lot of features use the same files. In this example I put the file in a
    # separate folder. Maybe a Karate builtin function for retrieving the full path of a file in this specific case would be
    # useful
    * def fullPathFile =
      """
            function(arg) {
             return Java.type('examples.Utility').getFullPath(arg);
            }
      """


  * def pdfFile = fullPathFile('files/pdf-test.pdf')

    Given driver uri
    And waitFor(uploadSelector).input(pdfFile)
    When submit().click(submitSelector)
    And delay(5000)
    Then match driver.text('#content > div > h3') == 'File Uploaded!'
    And match driver.text('#uploaded-files') contains 'pdf-test.pdf'

1 Ответ

0 голосов
/ 23 апреля 2020

Загрузка файлов - известная трудная проблема, которую нужно решить в автоматизации браузера. Нам понадобятся некоторые материалы от сообщества, но вот демонстрация, с которой я только что поэкспериментировал с использованием робота каратэ: https://github.com/intuit/karate/tree/develop/karate-robot

Feature:

Scenario:
* driver 'http://the-internet.herokuapp.com/upload'
* robot { app: '^Chrome', highlight: true }
* robot.click('choose-file.png')
* robot.input('/Users/pthomas3/Desktop')
* robot.input(Key.ENTER)
* robot.click('file-name.png')
* robot.input(Key.ENTER)
* delay(1000)
* click('#file-submit')
* delay(2000)
* screenshot()

Видео с казнью можно посмотреть здесь: https://twitter.com/ptrthomas/status/1253373486384295936

Другие возможные варианты:

a) Используйте возможности тестирования API Карате для загрузки multipart файла: https://github.com/intuit/karate#multipart -file - этого на самом деле в большинстве случаев достаточно, чтобы «завершить» имеющийся у вас поток. Например, для того же потока, который вы видите выше, он выглядит следующим образом:

* url 'http://the-internet.herokuapp.com/upload'
* multipart file file = { read: 'billie.png', filename: 'billie.png', contentType: 'image/png' }
* method post

И, как правило, вам может понадобиться добавить повара ie или двух, которые вы можете легко передать из браузер для API-теста / HTTP-клиента .

b) Другой вариант - это то, что я еще не пробовал, вы можете «подделать» часть пользовательского интерфейса, которая делает загрузите файл и замените его чем-то другим, если это поможет вам продвинуться вперед. См. Это: https://twitter.com/KarateDSL/status/1248996522357739521

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...