diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..18cb448 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,27 @@ +name: Build +on: [push,pull_request] +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + ruby-version: + - 2.0 + - 2.6 + - 2.7 + - 3.1 + - 3.2 + - 3.3 + - jruby-9.1 + - jruby-head + name: Ruby ${{ matrix.ruby-version }} sample + steps: + - uses: actions/checkout@v3 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby-version }} +# bundler-cache: true + - run: bundle install + - env: + CONVERT_API_SECRET: ${{ secrets.CONVERTAPI_SECRET }} + run: bundle exec rake spec diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..6e9f041 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,21 @@ +name: Publish gem to rubygems +on: + release: + types: [published] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + + # setup .gem/credentials + - run: mkdir -p ~/.gem + - env: + RUBYGEMS_API_KEY: ${{ secrets.RUBYGEMS_API_KEY }} + run: >- + echo -e "---\n:rubygems_api_key: ${RUBYGEMS_API_KEY}" > ~/.gem/credentials + - run: chmod 0600 ~/.gem/credentials + + - run: gem build convert_api.gemspec --output=release.gem + - run: gem push release.gem diff --git a/.ruby-version b/.ruby-version index 2bf1c1c..a0891f5 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -2.3.1 +3.3.4 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 0aa53bd..0000000 --- a/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -sudo: false -language: ruby -rvm: -- 2.1.0 -- 2.2.0 -- 2.3.0 -- 2.4.1 -- 2.5.1 -- ruby-head -- ruby-head-clang -- jruby-head -bundler_args: --jobs=3 --retry=3 --binstubs -env: - global: - secure: Pri+nCT6ayGYkjGO/WfMGkqk4DBKseJjQuWHWdft9YH2G+5dc7UKypDqmlfZvqwLPw2kybepKfh/utRGYsL5nfbET+3Ml8+2Bgaf0IT4Ej/3B5KIdFbivHmRp/NP/Dgh64M+5u1wKEEnw1NIMHwcanQDzPUDtaxqsw1xwowUL5Axr+UnJtWL2bP/RCED2JEgwhBQBFSMBXXwpSK2yFT7X1pInPWX2S0hELxj1UDefLDjp6kEnkrU/u+FjC9RhmYhusx2muXC4pHiqdNL0fDZStgginAQAd92FsMHQyzwewefCGRAg0g25ZmSGx5cHL4BZORdUnxaG9+AS9Wt17tZI2WS9eUBc9yyRU+R76aSo79uJj4RKi1Ljd3+4fyI/9BDz9a2koEgeDbYUHHf0dYaFSLXcOpnLBBPtr0qD02SUP1EcYTOe1/sNMweDLfN67E70YV69+ZqQeb+xgCbAeeoTOGJ9uKR2c91wSZwDjpTXXSLrNeNw98FPRyWxpfRRFQV29ZDPx/cfHt9gAVQVnd+ZBCAFwr353nqE8Ux1wtrxkexPkT8G+TXIgTvvYDfu2WmaO7qrZR2D6427jc4sgndwWfSPgiLw4eW1u3hCyaCnPBsviugtj1sTs2NfnLPdgtSUcKBd4xNbbVQoqZM1qTL139HvpZFB+jD8uoVtgWigUA= diff --git a/README.md b/README.md index b442e98..ef0655e 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,13 @@ [![Gem](https://img.shields.io/gem/v/convert_api.svg)](https://rubygems.org/gems/convert_api) -[![Build Status](https://secure.travis-ci.org/ConvertAPI/convertapi-ruby.svg)](http://travis-ci.org/ConvertAPI/convertapi-ruby) +[![Build Status](https://github.com/ConvertAPI/convertapi-ruby/actions/workflows/main.yml/badge.svg)](https://github.com/ConvertAPI/convertapi-ruby/actions) +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) + ## Convert your files with our online file conversion API -The ConvertAPI helps converting various file formats. Creating PDF and Images from various sources like Word, Excel, Powerpoint, images, web pages or raw HTML codes. Merge, Encrypt, Split, Repair and Decrypt PDF files. And many others files manipulations. In just few minutes you can integrate it into your application and use it easily. +ConvertAPI helps in converting various file formats. Creating PDF and Images from various sources like Word, Excel, Powerpoint, images, web pages or raw HTML codes. Merge, Encrypt, Split, Repair and Decrypt PDF files and many other file manipulations. You can integrate it into your application in just a few minutes and use it easily. ## Installation @@ -21,21 +23,21 @@ gem 'convert_api' ### Configuration -You can get your secret at https://www.convertapi.com/a +You can get your credentials at [https://www.convertapi.com/a/authentication](https://www.convertapi.com/a/authentication) ```ruby ConvertApi.configure do |config| - config.api_secret = 'your-api-secret' + config.api_credentials = 'api-token' end ``` ### File conversion -Example to convert file to PDF. All supported formats and options can be found -[here](https://www.convertapi.com). +Example to convert file to PDF. All supported formats and options can be found +[here](https://www.convertapi.com/doc/supported-formats). ```ruby -result = ConvertApi.convert('pdf', File: '/path/to/my_file.docx') +result = ConvertApi.convert('pdf', { File: '/path/to/my_file.docx' }) # save to file result.file.save('/path/to/save/file.pdf') @@ -57,7 +59,7 @@ conversion_cost = result.conversion_cost #### Convert file url ```ruby -result = ConvertApi.convert('pdf', File: 'https://website/my_file.docx') +result = ConvertApi.convert('pdf', { File: 'https://website/my_file.docx' }) ``` #### Specifying from format @@ -65,7 +67,7 @@ result = ConvertApi.convert('pdf', File: 'https://website/my_file.docx') ```ruby result = ConvertApi.convert( 'pdf', - { File: /path/to/my_file' }, + {File: /path/to/my_file'}, from_format: 'docx' ) ``` @@ -73,35 +75,57 @@ result = ConvertApi.convert( #### Additional conversion parameters ConvertAPI accepts extra conversion parameters depending on converted formats. All conversion -parameters and explanations can be found [here](https://www.convertapi.com). +parameters and explanations can be found [here](https://www.convertapi.com/doc/supported-formats). ```ruby result = ConvertApi.convert( 'pdf', - File: /path/to/my_file.docx', + {File: /path/to/my_file.docx', PageRange: '1-10', - PdfResolution: '150', + PdfResolution: '150'} ) ``` +#### Accessing result file properties + +You can access result file collection like this: + +```ruby +result = ConvertApi.convert('pdf', { File: 'https://website/my_file.docx' }) + +puts result.files[0].url +puts result.files[0].size +``` + ### User information -You can always check remaining seconds amount by fetching [user information](https://www.convertapi.com/doc/user). +You can always check your usage by fetching [user information](https://www.convertapi.com/doc/user). ```ruby user_info = ConvertApi.user -puts user_info['SecondsLeft'] +puts user_info['ConversionsConsumed'] ``` +### Alternative domain + +Set config `base_uri` attribute to use other service domains. Dedicated to the region [domain list](https://www.convertapi.com/doc/servers-location). + +```ruby +ConvertApi.configure do |config| + config.base_uri = URI('https://eu-v2.convertapi.com/') +end +``` + + ### More examples -You can find more advanced examples in the [examples/](https://github.com/ConvertAPI/convertapi-ruby/tree/master/examples) folder. +Find more advanced examples in the [examples/](https://github.com/ConvertAPI/convertapi-ruby/tree/master/examples) folder. ## Development -Run `CONVERT_API_SECRET=your_secret rake spec` to run the tests. +Run `CONVERT_API_SECRET=your_api_token rake spec` to run the tests. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). diff --git a/convert_api.gemspec b/convert_api.gemspec index 89311f9..cf71b76 100644 --- a/convert_api.gemspec +++ b/convert_api.gemspec @@ -21,7 +21,7 @@ Gem::Specification.new do |spec| spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] - spec.add_development_dependency 'bundler', '~> 1.16' - spec.add_development_dependency 'rake', '~> 10.0' + spec.add_development_dependency 'bundler' + spec.add_development_dependency 'rake', '>= 12.3.3' spec.add_development_dependency 'rspec', '~> 3.0' end diff --git a/examples/alternative_converter.rb b/examples/alternative_converter.rb deleted file mode 100644 index db36818..0000000 --- a/examples/alternative_converter.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'convert_api' -require 'tmpdir' - -ConvertApi.configure do |config| - config.api_secret = ENV['CONVERT_API_SECRET'] # your api secret -end - -# Example of saving Word docx to PDF using OpenOffice converter -# https://www.convertapi.com/doc-to-pdf/openofficetopdf - -# Use upload IO wrapper to upload file only once to the API -upload_io = ConvertApi::UploadIO.new(File.open('files/test.docx')) - -saved_files = ConvertApi - .convert('pdf', File: upload_io, converter: 'openofficetopdf') - .save_files(Dir.tmpdir) - -puts "The PDF saved to: #{saved_files}" \ No newline at end of file diff --git a/examples/conversions_chaining.rb b/examples/conversions_chaining.rb index 1443a3e..857de79 100644 --- a/examples/conversions_chaining.rb +++ b/examples/conversions_chaining.rb @@ -2,7 +2,7 @@ require 'tmpdir' ConvertApi.configure do |config| - config.api_secret = ENV['CONVERT_API_SECRET'] # your api secret + config.api_credentials = ENV['API_TOKEN'] # your api token end # Short example of conversions chaining, the PDF pages extracted and saved as separated JPGs and then ZIP'ed @@ -10,14 +10,14 @@ puts 'Converting PDF to JPG and compressing result files with ZIP' -jpg_result = ConvertApi.convert('jpg', File: 'files/test.pdf') +jpg_result = ConvertApi.convert('jpg', {File: 'files/test.pdf'}) puts "Conversions done. Cost: #{jpg_result.conversion_cost}. Total files created: #{jpg_result.files.count}" -zip_result = ConvertApi.convert('zip', Files: jpg_result.files) +zip_result = ConvertApi.convert('zip', {Files: jpg_result.files}) puts "Conversions done. Cost: #{zip_result.conversion_cost}. Total files created: #{zip_result.files.count}" saved_files = zip_result.save_files(Dir.tmpdir) -puts "File saved to #{saved_files}" +puts "File saved to #{saved_files}" \ No newline at end of file diff --git a/examples/convert_stream.rb b/examples/convert_stream.rb new file mode 100644 index 0000000..61a7555 --- /dev/null +++ b/examples/convert_stream.rb @@ -0,0 +1,24 @@ +require 'convert_api' +require 'tmpdir' + +ConvertApi.configure do |config| + config.api_credentials = ENV['API_TOKEN'] # your api token +end + +# Example of converting text to PDF +# https://www.convertapi.com/txt-to-pdf + +content = 'Test file body' + +io = StringIO.new +io.write(content) +io.rewind + +# Use upload IO wrapper to upload data to the API +upload_io = ConvertApi::UploadIO.new(io, 'test.txt') + +saved_files = ConvertApi + .convert('pdf', {File: upload_io}) + .save_files(Dir.tmpdir) + +puts "The PDF saved to: #{saved_files}" \ No newline at end of file diff --git a/examples/convert_url_to_pdf.rb b/examples/convert_url_to_pdf.rb index 166bf41..880886b 100644 --- a/examples/convert_url_to_pdf.rb +++ b/examples/convert_url_to_pdf.rb @@ -2,7 +2,7 @@ require 'tmpdir' ConvertApi.configure do |config| - config.api_secret = ENV['CONVERT_API_SECRET'] # your api secret + config.api_credentials = ENV['API_TOKEN'] # your api token end # Example of converting Web Page URL to PDF file @@ -20,4 +20,4 @@ saved_files = result.save_files(Dir.tmpdir) -puts "The web page PDF saved to #{saved_files}" +puts "The web page PDF saved to #{saved_files}" \ No newline at end of file diff --git a/examples/convert_word_to_pdf_and_png.rb b/examples/convert_word_to_pdf_and_png.rb index 023dd67..ad3b882 100644 --- a/examples/convert_word_to_pdf_and_png.rb +++ b/examples/convert_word_to_pdf_and_png.rb @@ -2,7 +2,7 @@ require 'tmpdir' ConvertApi.configure do |config| - config.api_secret = ENV['CONVERT_API_SECRET'] # your api secret + config.api_credentials = ENV['API_TOKEN'] # your api token end # Example of saving Word docx to PDF and to PNG @@ -13,7 +13,7 @@ upload_io = ConvertApi::UploadIO.new(File.open('files/test.docx')) saved_files = ConvertApi - .convert('pdf', File: upload_io) + .convert('pdf', {File: upload_io}) .save_files(Dir.tmpdir) puts "The PDF saved to: #{saved_files}" @@ -23,4 +23,4 @@ .convert('png', File: upload_io) .save_files(Dir.tmpdir) -puts "The PNG saved to: #{saved_files}" +puts "The PNG saved to: #{saved_files}" \ No newline at end of file diff --git a/examples/create_pdf_thumbnail.rb b/examples/create_pdf_thumbnail.rb index d64b057..7a08683 100644 --- a/examples/create_pdf_thumbnail.rb +++ b/examples/create_pdf_thumbnail.rb @@ -2,7 +2,7 @@ require 'tmpdir' ConvertApi.configure do |config| - config.api_secret = ENV['CONVERT_API_SECRET'] # your api secret + config.api_credentials = ENV['API_TOKEN'] # your api token end # Example of extracting first page from PDF and then chaining conversion PDF page to JPG. @@ -11,19 +11,19 @@ pdf_result = ConvertApi.convert( 'extract', - File: 'files/test.pdf', - PageRange: 1, + {File: 'files/test.pdf', + PageRange: 1} ) jpg_result = ConvertApi.convert( 'jpg', - File: pdf_result, + {File: pdf_result, ScaleImage: true, ScaleProportions: true, ImageHeight: 300, - ImageWidth: 300, + ImageWidth: 300} ) saved_files = jpg_result.save_files(Dir.tmpdir) -puts "The thumbnail saved to #{saved_files}" +puts "The thumbnail saved to #{saved_files}" \ No newline at end of file diff --git a/examples/retrieve_user_information.rb b/examples/retrieve_user_information.rb index 3280b16..52573b8 100644 --- a/examples/retrieve_user_information.rb +++ b/examples/retrieve_user_information.rb @@ -1,10 +1,10 @@ require 'convert_api' ConvertApi.configure do |config| - config.api_secret = ENV['CONVERT_API_SECRET'] # your api secret + config.api_credentials = ENV['API_TOKEN'] # your api token end # Retrieve user information # https://www.convertapi.com/doc/user -puts ConvertApi.user +puts ConvertApi.user \ No newline at end of file diff --git a/examples/split_and_merge_pdf.rb b/examples/split_and_merge_pdf.rb index 9a8a1e7..fd0aba4 100644 --- a/examples/split_and_merge_pdf.rb +++ b/examples/split_and_merge_pdf.rb @@ -2,19 +2,19 @@ require 'tmpdir' ConvertApi.configure do |config| - config.api_secret = ENV['CONVERT_API_SECRET'] # your api secret + config.api_credentials = ENV['API_TOKEN'] # your api token end # Example of extracting first and last pages from PDF and then merging them back to new PDF. # https://www.convertapi.com/pdf-to-split # https://www.convertapi.com/pdf-to-merge -split_result = ConvertApi.convert('split', File: 'files/test.pdf') +split_result = ConvertApi.convert('split', {File: 'files/test.pdf'}) files = [split_result.files.first, split_result.files.last] -merge_result = ConvertApi.convert('merge', Files: files) +merge_result = ConvertApi.convert('merge', {Files: files}) saved_files = merge_result.save_files(Dir.tmpdir) -puts "The PDF saved to #{saved_files}" +puts "The PDF saved to #{saved_files}" \ No newline at end of file diff --git a/lib/convert_api/client.rb b/lib/convert_api/client.rb index d9c0b9a..848aa05 100644 --- a/lib/convert_api/client.rb +++ b/lib/convert_api/client.rb @@ -30,7 +30,7 @@ class Client def get(path, params = {}, options = {}) handle_response do - request = Net::HTTP::Get.new(request_uri(path, params), DEFAULT_HEADERS) + request = Net::HTTP::Get.new(request_uri(path, params), headers_with_auth) http(options).request(request) end @@ -38,7 +38,7 @@ def get(path, params = {}, options = {}) def post(path, params, options = {}) handle_response do - request = Net::HTTP::Post.new(request_uri(path), DEFAULT_HEADERS) + request = Net::HTTP::Post.new(request_uri(path), headers_with_auth) request.form_data = build_form_data(params) http(options).request(request) @@ -48,7 +48,7 @@ def post(path, params, options = {}) def upload(io, filename) handle_response do request_uri = base_uri.path + 'upload' - encoded_filename = URI.encode(filename) + encoded_filename = CGI.escape(filename) headers = DEFAULT_HEADERS.merge( 'Content-Type' => 'application/octet-stream', @@ -91,22 +91,17 @@ def handle_http_exceptions raise(TimeoutError, e) end - def http(read_timeout: nil) + def http(options = {}) http = Net::HTTP.new(base_uri.host, base_uri.port) http.open_timeout = config.connect_timeout - http.read_timeout = read_timeout || config.read_timeout + http.read_timeout = options.fetch(:read_timeout, config.read_timeout) http.use_ssl = base_uri.scheme == 'https' # http.set_debug_output $stderr http end def request_uri(path, params = {}) - raise(SecretError, 'API secret not configured') if config.api_secret.nil? - - params_with_secret = params.merge(Secret: config.api_secret) - query = URI.encode_www_form(params_with_secret) - - base_uri.path + path + '?' + query + base_uri.path + path + '?' + URI.encode_www_form(params) end def build_form_data(params) @@ -123,6 +118,18 @@ def build_form_data(params) data end + def headers_with_auth + DEFAULT_HEADERS.merge(auth_headers) + end + + def auth_headers + { 'Authorization' => "Bearer #{api_credentials}" } + end + + def api_credentials + config.api_credentials || raise(AuthenticationError, 'API credentials not configured') + end + def base_uri config.base_uri end diff --git a/lib/convert_api/configuration.rb b/lib/convert_api/configuration.rb index 76fba27..c29cfbe 100644 --- a/lib/convert_api/configuration.rb +++ b/lib/convert_api/configuration.rb @@ -1,6 +1,6 @@ module ConvertApi class Configuration - attr_accessor :api_secret + attr_accessor :api_credentials attr_accessor :base_uri attr_accessor :connect_timeout attr_accessor :read_timeout @@ -12,11 +12,10 @@ class Configuration def initialize @base_uri = URI('https://v2.convertapi.com/') @connect_timeout = 5 - @read_timeout = 60 - @conversion_timeout = 180 + @read_timeout = 1800 @conversion_timeout_delta = 10 - @upload_timeout = 600 - @download_timeout = 600 + @upload_timeout = 1800 + @download_timeout = 1800 end end end diff --git a/lib/convert_api/errors.rb b/lib/convert_api/errors.rb index ccff5ad..bdf78d0 100644 --- a/lib/convert_api/errors.rb +++ b/lib/convert_api/errors.rb @@ -1,6 +1,6 @@ module ConvertApi class Error < StandardError; end - class SecretError < Error; end + class AuthenticationError < Error; end class FileNameError < Error; end class TimeoutError < Error; end class ConnectionFailed < Error; end diff --git a/lib/convert_api/format_detector.rb b/lib/convert_api/format_detector.rb index 1a10229..bb95a79 100644 --- a/lib/convert_api/format_detector.rb +++ b/lib/convert_api/format_detector.rb @@ -1,21 +1,28 @@ module ConvertApi class FormatDetector - def initialize(resource) + ANY_FORMAT = 'any' + + def initialize(resource, to_format) @resource = resource + @to_format = to_format end def run + return ANY_FORMAT if archive? return @resource.file_ext.downcase if @resource.is_a?(UploadIO) - format_from_path + format_from_path || raise(FormatError, 'Unable to detect format') end private + def archive? + @to_format.to_s.downcase == 'zip' + end + def format_from_path extension = File.extname(path).downcase - format = extension[1..-1] - format || raise(FormatError, 'Unable to detect format') + extension[1..-1] end def path diff --git a/lib/convert_api/result_file.rb b/lib/convert_api/result_file.rb index c3b557c..9c1f069 100644 --- a/lib/convert_api/result_file.rb +++ b/lib/convert_api/result_file.rb @@ -21,7 +21,7 @@ def size end def io - @io ||= open(url, download_options) + @io ||= URI.parse(url).open(download_options) end def save(path) diff --git a/lib/convert_api/task.rb b/lib/convert_api/task.rb index 1781a7f..85fcc1f 100644 --- a/lib/convert_api/task.rb +++ b/lib/convert_api/task.rb @@ -14,13 +14,12 @@ def run ) from_format = @from_format || detect_format(params) - read_timeout = @conversion_timeout + config.conversion_timeout_delta - converter = params[:converter] ? "/converter/#{params[:converter]}" : '' + read_timeout = @conversion_timeout + config.conversion_timeout_delta if @conversion_timeout response = ConvertApi.client.post( - "convert/#{from_format}/to/#{@to_format}#{converter}", + "convert/#{from_format}/to/#{@to_format}", params, - read_timeout: read_timeout + read_timeout: read_timeout, ) Result.new(response) @@ -32,10 +31,10 @@ def normalize_params(params) result = {} symbolize_keys(params).each do |key, value| - case key - when :File - result[:File] = FileParam.build(value) - when :Files + case + when key != :StoreFile && key.to_s.end_with?('File') + result[key] = FileParam.build(value) + when key == :Files result[:Files] = files_batch(value) else result[key] = value @@ -66,7 +65,7 @@ def detect_format(params) resource = params[:File] || Array(params[:Files]).first - FormatDetector.new(resource).run + FormatDetector.new(resource, @to_format).run end def config diff --git a/lib/convert_api/version.rb b/lib/convert_api/version.rb index dad6693..bf3847f 100644 --- a/lib/convert_api/version.rb +++ b/lib/convert_api/version.rb @@ -1,3 +1,3 @@ module ConvertApi - VERSION = '1.2.0' -end \ No newline at end of file + VERSION = '3.0.0' +end diff --git a/spec/convert_api/format_detector_spec.rb b/spec/convert_api/format_detector_spec.rb index b56ae63..4fbe7d8 100644 --- a/spec/convert_api/format_detector_spec.rb +++ b/spec/convert_api/format_detector_spec.rb @@ -1,11 +1,19 @@ RSpec.describe ConvertApi::FormatDetector, '#run' do - subject { described_class.new(resource).run } + subject { described_class.new(resource, to_format).run } + + let(:to_format) { 'pdf' } context 'with file name' do let(:resource) { 'test.txt' } it { is_expected.to eq('txt') } end + context 'when archiving' do + let(:resource) { 'test.txt' } + let(:to_format) { 'zip' } + it { is_expected.to eq('any') } + end + context 'with file path' do let(:resource) { '/some/path/test.txt' } it { is_expected.to eq('txt') } diff --git a/spec/convert_api/task_spec.rb b/spec/convert_api/task_spec.rb index 6ad393a..d8b87c8 100644 --- a/spec/convert_api/task_spec.rb +++ b/spec/convert_api/task_spec.rb @@ -1,17 +1,42 @@ -RSpec.describe ConvertApi::Task do +RSpec.describe ConvertApi::Task, '#run' do + subject { task.run } + let(:task) { described_class.new(from_format, to_format, params) } let(:from_format) { 'txt' } let(:to_format) { 'pdf' } - let(:params) { { File: 'https://www.w3.org/TR/PNG/iso_8859-1.txt' } } + let(:params) { { File: file } } + let(:file) { 'https://www.w3.org/TR/2003/REC-PNG-20031110/iso_8859-1.txt' } + let(:result) { double } + + it 'executes task and returns result' do + expect(ConvertApi.client).to( + receive(:post).with('convert/txt/to/pdf', instance_of(Hash), instance_of(Hash)).and_return(result) + ) + + expect(subject).to be_instance_of(ConvertApi::Result) + end + + context 'when file is instance of ResultFile' do + let(:file) { ConvertApi::ResultFile.new('Url' => 'testurl') } + let(:expected_params) { hash_including(File: 'testurl') } - describe '#run' do - subject { task.run } + it 'uses file url' do + expect(ConvertApi.client).to( + receive(:post).with('convert/txt/to/pdf', expected_params, instance_of(Hash)).and_return(result) + ) + + expect(subject).to be_instance_of(ConvertApi::Result) + end + end - let(:result) { double } + context 'when multiple file params' do + let(:file) { ConvertApi::ResultFile.new('Url' => 'testurl') } + let(:params) { { File: file, CompareFile: file } } + let(:expected_params) { hash_including(File: 'testurl', CompareFile: 'testurl') } - it 'executes task and returns result' do + it 'uses multiple file urls' do expect(ConvertApi.client).to( - receive(:post).with('convert/txt/to/pdf', instance_of(Hash), instance_of(Hash)).and_return(result) + receive(:post).with('convert/txt/to/pdf', expected_params, instance_of(Hash)).and_return(result) ) expect(subject).to be_instance_of(ConvertApi::Result) diff --git a/spec/convert_api_spec.rb b/spec/convert_api_spec.rb index 31dab7d..85fc638 100644 --- a/spec/convert_api_spec.rb +++ b/spec/convert_api_spec.rb @@ -5,20 +5,20 @@ it 'has configuration defaults' do expect(described_class.config.base_uri).not_to be_nil expect(described_class.config.connect_timeout).not_to be_nil - expect(described_class.config.conversion_timeout).not_to be_nil + expect(described_class.config.conversion_timeout).to be_nil end describe '.configure' do - let(:api_secret) { 'test_secret' } + let(:api_credentials) { 'test_secret' } let(:conversion_timeout) { 20 } it 'configures' do described_class.configure do |config| - config.api_secret = api_secret + config.api_credentials = api_credentials config.conversion_timeout = conversion_timeout end - expect(described_class.config.api_secret).to eq(api_secret) + expect(described_class.config.api_credentials).to eq(api_credentials) expect(described_class.config.conversion_timeout).to eq(conversion_timeout) end end @@ -51,12 +51,6 @@ it_behaves_like 'successful conversion' - context 'with web resource' do - let(:params) { { Url: 'http://convertapi.com' } } - - it_behaves_like 'successful conversion' - end - context 'with web resource' do let(:from_format) { 'web' } let(:params) { { Url: 'http://convertapi.com' } } @@ -87,7 +81,7 @@ ConvertApi::Result.new( 'ConversionCost' => 1, 'Files' => [ - 'Url' => 'https://www.w3.org/TR/PNG/iso_8859-1.txt', + 'Url' => 'https://www.w3.org/TR/2003/REC-PNG-20031110/iso_8859-1.txt', ], ) end @@ -95,19 +89,17 @@ it_behaves_like 'successful conversion' end - context 'when secret is not set' do - before { ConvertApi.config.api_secret = nil } + context 'when has error' do + it 'raises error without credentials' do + described_class.config.api_credentials = nil - it 'raises error' do - expect { subject }.to raise_error(ConvertApi::SecretError, /not configured/) + expect { subject }.to raise_error(ConvertApi::AuthenticationError, /not configured/) end - end - context 'with invalid secret' do - before { ConvertApi.config.api_secret = 'invalid' } + it 'with invalid credentials' do + described_class.config.api_credentials = 'invalid' - it 'raises error' do - expect { subject }.to raise_error(ConvertApi::ClientError, /bad secret/) + expect { subject }.to raise_error(ConvertApi::ClientError) end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 833b9c4..20b8bf4 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -9,6 +9,6 @@ end config.before(:each) do - ConvertApi.config.api_secret = ENV['CONVERT_API_SECRET'] + ConvertApi.config.api_credentials = ENV['CONVERT_API_SECRET'] end end