diff --git a/.rubocop.yml b/.rubocop.yml deleted file mode 100644 index e8d01321..00000000 --- a/.rubocop.yml +++ /dev/null @@ -1,8 +0,0 @@ -inherit_from: .rubocop_todo.yml - -Metrics/LineLength: - Enabled: false -Style/EmptyLinesAroundModuleBody: - Enabled: false -Style/EmptyLinesAroundClassBody: - Enabled: false diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml deleted file mode 100644 index c4b6738b..00000000 --- a/.rubocop_todo.yml +++ /dev/null @@ -1,22 +0,0 @@ -# This configuration was generated by -# `rubocop --auto-gen-config` -# on 2016-01-07 12:11:06 -0500 using RuboCop version 0.35.1. -# The point is for the user to remove these configuration records -# one by one as the offenses are removed from the code base. -# Note that changes in the inspected code, or installation of new -# versions of RuboCop, may require this file to be generated again. - -# Offense count: 1 -# Configuration parameters: CountComments. -Metrics/ClassLength: - Max: 169 - -# Offense count: 1 -# Configuration parameters: CountComments. -Metrics/MethodLength: - Max: 14 - -# Offense count: 9 -Style/AccessorMethodName: - Exclude: - - 'lib/mailgun/messages/message_builder.rb' diff --git a/Gemfile b/Gemfile index 23028bb5..61025da8 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,9 @@ +# frozen_string_literal: true + source 'https://rubygems.org' # Specify your gem's dependencies in mailgun.gemspec gemspec -gem 'mini_mime' gem 'json', '~> 2.1', platform: :mri_19 +gem 'mini_mime' diff --git a/Rakefile b/Rakefile index cd5a36ad..0dfbb27c 100644 --- a/Rakefile +++ b/Rakefile @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'bundler/gem_tasks' require 'rake' require 'rspec/core/rake_task' @@ -9,7 +11,7 @@ end desc 'Run unit specs' RSpec::Core::RakeTask.new('spec:unit') do |t| - t.rspec_opts = %w(--colour --format documentation) + t.rspec_opts = %w[--colour --format documentation] t.pattern = 'spec/unit/*_spec.rb', 'spec/unit/*/*_spec.rb' end @@ -17,13 +19,13 @@ desc 'Run integration specs' # Before running integration tests, you need to specify # a valid API KEY in the spec/spec_helper.rb file. RSpec::Core::RakeTask.new('spec:integration') do |t| - t.rspec_opts = %w(--colour --format documentation) + t.rspec_opts = %w[--colour --format documentation] t.pattern = 'spec/integration/*_spec.rb' end desc 'Run all tests' RSpec::Core::RakeTask.new('spec:all') do |t| - t.rspec_opts = %w(--colour --format documentation) + t.rspec_opts = %w[--colour --format documentation] t.pattern = 'spec/**/*_spec.rb' end diff --git a/lib/mailgun-ruby.rb b/lib/mailgun-ruby.rb index caefcf73..3537d741 100644 --- a/lib/mailgun-ruby.rb +++ b/lib/mailgun-ruby.rb @@ -1,2 +1,4 @@ +# frozen_string_literal: true + require_relative 'mailgun' require_relative 'railgun' if defined?(Rails) && defined?(ActionMailer) diff --git a/lib/mailgun.rb b/lib/mailgun.rb index 9e301079..f91ef6bf 100644 --- a/lib/mailgun.rb +++ b/lib/mailgun.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # require ruby dependencies require 'json' require 'openssl' @@ -16,7 +18,7 @@ require 'mailgun/helpers/api_version_checker' # load zeitwerk -Zeitwerk::Loader.for_gem.tap do |loader| # rubocop:disable Style/SymbolProc +Zeitwerk::Loader.for_gem.tap do |loader| loader.ignore("#{__dir__}/mailgun-ruby.rb") loader.ignore("#{__dir__}/railgun.rb") loader.ignore("#{__dir__}/railgun") @@ -41,7 +43,6 @@ # # See the Github documentation for full examples. module Mailgun - class << self attr_accessor :api_host, :api_key, @@ -56,7 +57,6 @@ def configure yield self true end - alias_method :config, :configure + alias config configure end - end diff --git a/lib/mailgun/address.rb b/lib/mailgun/address.rb index 1ea3511b..1aa2652e 100644 --- a/lib/mailgun/address.rb +++ b/lib/mailgun/address.rb @@ -1,5 +1,6 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # Mailgun::Address is a simple interface to the Email Validation API. class Address def initialize(api_key = Mailgun.api_key, api_host = Mailgun.api_host) @@ -10,12 +11,11 @@ def initialize(api_key = Mailgun.api_key, api_host = Mailgun.api_host) # # @param [String] address Email address to validate (max 512 chars.) def validate(address, mailbox_verification = false) - params = {address: address} + params = { address: address } params[:mailbox_verification] = true if mailbox_verification - res = @client.get "address/validate", params - return res.to_h! + res = @client.get 'address/validate', params + res.to_h! end end - end diff --git a/lib/mailgun/chains.rb b/lib/mailgun/chains.rb index a909bc46..835414ed 100644 --- a/lib/mailgun/chains.rb +++ b/lib/mailgun/chains.rb @@ -1,8 +1,8 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # Public constants used throughout class Chains - # maximum campaign ids per message MAX_CAMPAIGN_IDS = 3 @@ -11,6 +11,5 @@ class Chains # maximum recipients per message or batch MAX_RECIPIENTS = 1000 - end end diff --git a/lib/mailgun/client.rb b/lib/mailgun/client.rb index 74fd5f35..5cbb2586 100644 --- a/lib/mailgun/client.rb +++ b/lib/mailgun/client.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Mailgun # A Mailgun::Client object is used to communicate with the Mailgun API. It is a # wrapper around Faraday so you don't have to worry about the HTTP aspect @@ -5,28 +7,27 @@ module Mailgun # # See the Github documentation for full examples. class Client - SUBACCOUNT_HEADER = 'X-Mailgun-On-Behalf-Of'.freeze + SUBACCOUNT_HEADER = 'X-Mailgun-On-Behalf-Of' def initialize(api_key = Mailgun.api_key, api_host = Mailgun.api_host || 'api.mailgun.net', - api_version = Mailgun.api_version || 'v3', + api_version = Mailgun.api_version || 'v3', ssl = true, - test_mode = !!Mailgun.test_mode, + test_mode = !Mailgun.test_mode.nil?, timeout = nil, proxy_url = Mailgun.proxy_url) - endpoint = endpoint_generator(api_host, api_version, ssl) request_options = { url: endpoint, proxy: proxy_url, - ssl: {verify: ssl}, + ssl: { verify: ssl }, headers: { - 'User-Agent' => "mailgun-sdk-ruby/#{Mailgun::VERSION}", - 'Accept' =>'*/*' - } + 'User-Agent' => "mailgun-sdk-ruby/#{Mailgun::VERSION}", + 'Accept' => '*/*' + } } - request_options.merge!(request: {timeout: timeout}) if timeout + request_options.merge!(request: { timeout: timeout }) if timeout @http_client = build_http_client(api_key, request_options) @@ -55,7 +56,7 @@ def set_api_key(api_key) # Add subaccount id to headers def set_subaccount(subaccount_id) - @http_client.headers = @http_client.headers.merge!({ SUBACCOUNT_HEADER => subaccount_id }) + @http_client.headers.merge!({ SUBACCOUNT_HEADER => subaccount_id }) end # Reset subaccount for primary usage @@ -71,9 +72,7 @@ def test_mode? end # @return [String] client api version - def api_version - @api_version - end + attr_reader :api_version # Provides a store of all the emails sent in test mode so you can check them. # @@ -91,12 +90,12 @@ def self.deliveries def send_message(working_domain, data) perform_data_validation(working_domain, data) - if test_mode? then + if test_mode? Mailgun::Client.deliveries << data.dup return Response.from_hash( { - :body => "{\"id\": \"test-mode-mail-#{SecureRandom.uuid}@localhost\", \"message\": \"Queued. Thank you.\"}", - :status => 200, + body: "{\"id\": \"test-mode-mail-#{SecureRandom.uuid}@localhost\", \"message\": \"Queued. Thank you.\"}", + status: 200 } ) end @@ -106,7 +105,7 @@ def send_message(working_domain, data) # Remove nil values from the data hash # Submitting nils to the API will likely cause an error. # See also: https://github.com/mailgun/mailgun-ruby/issues/32 - data = data.select { |k, v| v != nil } + data = data.reject { |_k, v| v.nil? } if data.key?(:message) if data[:message].is_a?(String) @@ -119,7 +118,7 @@ def send_message(working_domain, data) when MessageBuilder post("#{working_domain}/messages", data.message) else - fail ParameterError.new('Unknown data type for data parameter.', data) + raise ParameterError.new('Unknown data type for data parameter.', data) end end @@ -134,8 +133,8 @@ def send_message(working_domain, data) def post(resource_path, data, headers = {}) response = @http_client.post(resource_path, data, headers) Response.new(response) - rescue => err - raise communication_error err + rescue StandardError => e + raise communication_error e end # Generic Mailgun GET Handler @@ -151,8 +150,8 @@ def get(resource_path, params = {}, accept = '*/*') response = @http_client.get(resource_path, params, headers) Response.new(response) - rescue => err - raise communication_error(err) + rescue StandardError => e + raise communication_error(e) end # Generic Mailgun PUT Handler @@ -165,8 +164,8 @@ def get(resource_path, params = {}, accept = '*/*') def put(resource_path, data, headers = {}) response = @http_client.put(resource_path, data, headers) Response.new(response) - rescue => err - raise communication_error err + rescue StandardError => e + raise communication_error e end # Generic Mailgun DELETE Handler @@ -188,8 +187,8 @@ def delete(resource_path, params = nil, body_params = false) @http_client.delete(resource_path) end Response.new(response) - rescue => err - raise communication_error err + rescue StandardError => e + raise communication_error e end # Constructs a Suppressions client for the given domain. @@ -221,7 +220,7 @@ def convert_string_to_file(string) # @param [Boolean] ssl True, SSL. False, No SSL. # @return [string] concatenated URL string def endpoint_generator(api_host, api_version, ssl) - ssl ? scheme = 'https' : scheme = 'http' + scheme = ssl ? 'https' : 'http' if api_version "#{scheme}://#{api_host}/#{api_version}" else @@ -235,28 +234,33 @@ def endpoint_generator(api_host, api_version, ssl) def communication_error(e) if e.respond_to?(:response) && e.response return case e.response_status - when Unauthorized::CODE - Unauthorized.new(e.message, e.response) - when BadRequest::CODE - BadRequest.new(e.message, e.response) - else - CommunicationError.new(e.message, e.response) - end + when Unauthorized::CODE + Unauthorized.new(e.message, e.response) + when BadRequest::CODE + BadRequest.new(e.message, e.response) + else + CommunicationError.new(e.message, e.response) + end end CommunicationError.new(e.message) end def perform_data_validation(working_domain, data) message = data.respond_to?(:message) ? data.message : data - fail ParameterError.new('Missing working domain', working_domain) unless working_domain - fail ParameterError.new( - 'Missing `to` recipient, message should contain at least 1 recipient', - working_domain - ) if message.fetch('to', []).empty? && message.fetch(:to, []).empty? - fail ParameterError.new( + raise ParameterError.new('Missing working domain', working_domain) unless working_domain + + if message.fetch('to', []).empty? && message.fetch(:to, []).empty? + raise ParameterError.new( + 'Missing `to` recipient, message should contain at least 1 recipient', + working_domain + ) + end + return unless message.fetch('from', []).empty? && message.fetch(:from, []).empty? + + raise ParameterError.new( 'Missing a `from` sender, message should contain at least 1 `from` sender', working_domain - ) if message.fetch('from', []).empty? && message.fetch(:from, []).empty? + ) end def build_http_client(api_key, request_options) diff --git a/lib/mailgun/domains/domains.rb b/lib/mailgun/domains/domains.rb index 17d77076..a4925535 100644 --- a/lib/mailgun/domains/domains.rb +++ b/lib/mailgun/domains/domains.rb @@ -1,5 +1,6 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # A Mailgun::Domains object is a simple CRUD interface to Mailgun Domains. # Uses Mailgun class Domains @@ -67,7 +68,6 @@ def update(domain, options = {}) @client.put("domains/#{domain}", options).to_h end - # Public: Verify domain # # domain - [String] Domain name @@ -101,7 +101,7 @@ def remove(domain) # # Returns [Hash] with message key def list_domain_keys(options = {}) - @client.get("dkim/keys", options).to_h + @client.get('dkim/keys', options).to_h end # Public: Create a domain key @@ -114,7 +114,7 @@ def list_domain_keys(options = {}) # # Returns [Hash] with message key def create_domain_key(options = {}) - @client.post("dkim/keys", options).to_h + @client.post('dkim/keys', options).to_h end # Public: Delete a domain key. @@ -125,7 +125,7 @@ def create_domain_key(options = {}) # # Returns [Hash] with message key def delete_domain_key(options = {}) - @client.delete("dkim/keys", options).to_h + @client.delete('dkim/keys', options).to_h end # Public: Activate a domain key for a specified authority and selector. @@ -258,7 +258,6 @@ def generate_domain_tracking_certificate(domain, options = {}) # ==== End of Domain::Tracking methods ==== - # ==== Domain::DKIM_Security methods ==== # Public: Tracking Certificate: Generate @@ -338,13 +337,13 @@ def delete_smtp_credentials(domain, login) # # Returns [Array] A list of domains (hash) def get_domain_stats(domain, options = {}) - fail(ParameterError, 'No domain given to list stats on Mailgun', caller) unless domain + raise(ParameterError, 'No domain given to list stats on Mailgun', caller) unless domain + @client.get("#{domain}/stats/total", options).to_h end # ==== End of Reporting::Stats methods ==== - enforces_api_version 'v1', :list_domain_keys, :create_domain_key, :delete_domain_key, :dkim_rotation, :dkim_rotate enforces_api_version 'v2', :get_domain_tracking_certificate, :regenerate_domain_tracking_certificate, diff --git a/lib/mailgun/events/events.rb b/lib/mailgun/events/events.rb index b5e4b2c9..5ed0ad88 100644 --- a/lib/mailgun/events/events.rb +++ b/lib/mailgun/events/events.rb @@ -1,5 +1,6 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # A Mailgun::Events object makes it really simple to consume # Mailgun's events from the Events endpoint. # @@ -100,7 +101,7 @@ def extract_paging(response) # Returns a String of the partial URI if the given url follows the regular API format # Returns nil in other cases (e.g. when given nil, or an irrelevant url) def extract_endpoint_from(url = nil) - URI.parse(url).path[/\/v[\d]\/#{@domain}\/events\/(.+)/,1] + URI.parse(url).path[%r{/v\d/#{@domain}/events/(.+)}, 1] rescue URI::InvalidURIError nil end @@ -112,8 +113,8 @@ def extract_endpoint_from(url = nil) # Returns a String of the partial URI def construct_url(paging = nil) return "#{@domain}/events/#{paging}" if paging + "#{@domain}/events" end - end end diff --git a/lib/mailgun/exceptions/exceptions.rb b/lib/mailgun/exceptions/exceptions.rb index 7ae62215..30d17e5c 100644 --- a/lib/mailgun/exceptions/exceptions.rb +++ b/lib/mailgun/exceptions/exceptions.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Mailgun module Exceptions end @@ -6,7 +8,6 @@ module Exceptions # Inherits from StandardError (previously RuntimeError) as not all errors are # runtime errors. class Error < StandardError - # Public: get an object an error is instantiated with attr_reader :object @@ -35,7 +36,7 @@ class CommunicationError < Error attr_reader :status # Public: fallback if there is no response status on the object - NOCODE = 000 + NOCODE = 0o00 FORBIDDEN = 'Forbidden' # Public: initialization of new error given a message and/or object @@ -46,10 +47,10 @@ class CommunicationError < Error def initialize(message = nil, response = nil) @response = response @status = if response.nil? - NOCODE - else - response[:status] - end + NOCODE + else + response[:status] + end begin json = JSON.parse(response[:body]) @@ -57,13 +58,13 @@ def initialize(message = nil, response = nil) rescue JSON::ParserError api_message = response.response_body rescue NoMethodError - api_message = "Unknown API error" - rescue + api_message = 'Unknown API error' + rescue StandardError api_message = 'Unknown API error' end - message = message || '' - message = message + ': ' + (api_message || "") + message ||= '' + message = "#{message}: #{api_message || ''}" super(message, response) rescue NoMethodError, JSON::ParserError @@ -78,7 +79,7 @@ class Unauthorized < CommunicationError CODE = 401 def initialize(error_message, response) - error_message = error_message + ' - Invalid Domain or API key' + error_message += ' - Invalid Domain or API key' super(error_message, response) end end @@ -87,9 +88,5 @@ def initialize(error_message, response) # Inherits from Mailgun::CommunicationError class BadRequest < CommunicationError CODE = 400 - - def initialize(error_message, response) - super(error_message, response) - end end end diff --git a/lib/mailgun/helpers/api_version_checker.rb b/lib/mailgun/helpers/api_version_checker.rb index b8682fee..333d42d7 100644 --- a/lib/mailgun/helpers/api_version_checker.rb +++ b/lib/mailgun/helpers/api_version_checker.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Mailgun module ApiVersionChecker def self.included(base) @@ -35,7 +37,10 @@ def warn_unless_api_version(expected_version) end def require_api_version(expected_version) - fail(ParameterError, "Client api version must be #{expected_version}", caller) unless @client.api_version == expected_version + return if @client.api_version == expected_version + + raise(ParameterError, "Client api version must be #{expected_version}", + caller) end end end diff --git a/lib/mailgun/lists/opt_in_handler.rb b/lib/mailgun/lists/opt_in_handler.rb index e436737e..0ff822df 100644 --- a/lib/mailgun/lists/opt_in_handler.rb +++ b/lib/mailgun/lists/opt_in_handler.rb @@ -1,11 +1,11 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # Public: Provides methods for creating and handling opt-in URLs, # particularlly for mailing lists. # # See: https://github.com/mailgun/mailgun-ruby/blob/master/OptInHandler.md class OptInHandler - # Generates a hash that can be used to validate opt-in recipients. Encodes # all the necessary data in the URL. # @@ -46,6 +46,7 @@ def self.validate_hash(secret_app_id, unique_hash) if generated_hash == hash_provided return { 'recipient_address' => inner_payload['r'], 'mailing_list' => inner_payload['l'] } end + false end @@ -58,13 +59,10 @@ def self.base64_encode(input) def self.base64_decode(input) # TODO: Condition can be droped if Ruby >= 2.4.0 if input.respond_to?(:unpack1) - input.unpack1('m') - else - input.unpack('m').first end + input.unpack1('m') end private_class_method :base64_encode, :base64_decode end - end diff --git a/lib/mailgun/logs/logs.rb b/lib/mailgun/logs/logs.rb index d4d41cc7..75d04c1a 100644 --- a/lib/mailgun/logs/logs.rb +++ b/lib/mailgun/logs/logs.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Mailgun # A Mailgun::Logs object is a simple interface to Mailgun Logs. # Uses Mailgun @@ -30,8 +32,8 @@ def initialize(client = Mailgun::Client.new(Mailgun.api_key, Mailgun.api_host || # limit - [Integer] The maximum number of items returned (100 max). # # Returns [Hash] Logs - def account_logs(options={}) - @client.post('analytics/logs', options.to_json, { "Content-Type" => "application/json" }).to_h! + def account_logs(options = {}) + @client.post('analytics/logs', options.to_json, { 'Content-Type' => 'application/json' }).to_h! end end end diff --git a/lib/mailgun/messages/batch_message.rb b/lib/mailgun/messages/batch_message.rb index dae331e3..a65786c4 100644 --- a/lib/mailgun/messages/batch_message.rb +++ b/lib/mailgun/messages/batch_message.rb @@ -1,5 +1,6 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # A Mailgun::BatchMessage object is used to create a valid payload # for Batch Sending. Batch Sending can be difficult to implement, therefore # this code makes it dead simple to send millions of messages in batches of @@ -18,7 +19,6 @@ module Mailgun # # See the Github documentation for full examples. class BatchMessage < MessageBuilder - attr_reader :message_ids, :domain, :recipient_variables # Public: Creates a new BatchMessage object. @@ -68,9 +68,10 @@ def finalize # # @return [Boolean] def any_recipients_left? - return true if @counters[:recipients][:to] > 0 - return true if @counters[:recipients][:cc] > 0 - return true if @counters[:recipients][:bcc] > 0 + return true if @counters[:recipients][:to].positive? + return true if @counters[:recipients][:cc].positive? + return true if @counters[:recipients][:bcc].positive? + false end @@ -86,7 +87,7 @@ def send_message @message[rkey] = @message[rkey].first if @message.key?(rkey) response = @client.send_message(@domain, @message).to_h! - message_id = response['id'].gsub(/\>|\|= Mailgun::Chains::MAX_RECIPIENTS - fail Mailgun::ParameterError, 'Too many recipients added to message.', address + raise Mailgun::ParameterError, 'Too many recipients added to message.', address end compiled_address = parse_address(address, variables) @@ -68,7 +68,7 @@ def set_from_address(address, variables = nil) # @return [void] def reply_to(address, variables = nil) compiled_address = parse_address(address, variables) - header("reply-to", compiled_address) + header('reply-to', compiled_address) end # Set a subject for the message object @@ -180,7 +180,10 @@ def set_dkim(mode) # @param [String] campaign_id A defined campaign ID to add to the message. # @return [void] def add_campaign_id(campaign_id) - fail(Mailgun::ParameterError, 'Too many campaigns added to message.', campaign_id) if @counters[:attributes][:campaign_id] >= Mailgun::Chains::MAX_CAMPAIGN_IDS + if @counters[:attributes][:campaign_id] >= Mailgun::Chains::MAX_CAMPAIGN_IDS + raise(Mailgun::ParameterError, 'Too many campaigns added to message.', + campaign_id) + end set_multi_complex('o:campaign', campaign_id) @counters[:attributes][:campaign_id] += 1 @@ -192,8 +195,9 @@ def add_campaign_id(campaign_id) # @return [void] def add_tag(tag) if @counters[:attributes][:tag] >= Mailgun::Chains::MAX_TAGS - fail Mailgun::ParameterError, 'Too many tags added to message.', tag + raise Mailgun::ParameterError, 'Too many tags added to message.', tag end + set_multi_complex('o:tag', tag) @counters[:attributes][:tag] += 1 end @@ -255,7 +259,8 @@ def set_delivery_time(timestamp) # @param [Hash] data Either a hash or JSON string. # @return [void] def header(name, data) - fail(Mailgun::ParameterError, 'Header name for message must be specified') if name.to_s.empty? + raise(Mailgun::ParameterError, 'Header name for message must be specified') if name.to_s.empty? + begin jsondata = make_json data set_single("h:#{name}", jsondata) @@ -278,7 +283,8 @@ def set_custom_data(name, data) # can not be converted to JSON, ParameterError will be raised. # @return [void] def variable(name, data) - fail(Mailgun::ParameterError, 'Variable name must be specified') if name.to_s.empty? + raise(Mailgun::ParameterError, 'Variable name must be specified') if name.to_s.empty? + begin jsondata = make_json data set_single("v:#{name}", jsondata) @@ -308,6 +314,7 @@ def add_custom_parameter(name, data) def message_id(data = nil) key = 'h:Message-Id' return @message.delete(key) if data.to_s.empty? + set_single(key, data) end @@ -326,6 +333,7 @@ def set_message_id(data = nil) def template(template_name = nil) key = 'template' return @message.delete(key) if template_name.to_s.empty? + set_single(key, template_name) end @@ -337,6 +345,7 @@ def template(template_name = nil) def template_version(version = nil) key = 't:version' return @message.delete(key) if version.to_s.empty? + set_single(key, version) end @@ -358,7 +367,7 @@ def template_text(mode) # @param [String] value The value of the parameter. # @return [void] def set_single(parameter, value) - @message[parameter] = value ? value : '' + @message[parameter] = value || '' end # Sets values within the multidict, however, prevents @@ -397,8 +406,9 @@ def add_faraday_attachment(parameter, attachment, filename) # @param [String] value The item to convert # @return [void] def bool_lookup(value) - return 'yes' if %w(true yes yep).include? value.to_s.downcase - return 'no' if %w(false no nope).include? value.to_s.downcase + return 'yes' if %w[true yes yep].include? value.to_s.downcase + return 'no' if %w[false no nope].include? value.to_s.downcase + warn 'WARN: for bool type actions next values are preferred: true yes yep | false no nope | htmlonly' value end @@ -409,7 +419,7 @@ def bool_lookup(value) # @return [void] def valid_json?(json_) JSON.parse(json_) - return true + true rescue JSON::ParserError false end @@ -422,8 +432,9 @@ def valid_json?(json_) def make_json(obj) return JSON.parse(obj).to_json if obj.is_a?(String) return obj.to_json if obj.is_a?(Hash) + JSON.generate(obj).to_json - rescue + rescue StandardError raise Mailgun::ParameterError, 'Provided data could not be made into JSON. Try a JSON string or Hash.', obj end @@ -436,9 +447,9 @@ def make_json(obj) # @return [void] def parse_address(address, vars) return address unless vars.is_a? Hash - fail(Mailgun::ParameterError, 'Email address not specified') unless address.is_a? String - if vars['full_name'] != nil && (vars['first'] != nil || vars['last'] != nil) - fail(Mailgun::ParameterError, 'Must specify at most one of full_name or first/last. Vars passed: #{vars}') + raise(Mailgun::ParameterError, 'Email address not specified') unless address.is_a? String + if !vars['full_name'].nil? && (!vars['first'].nil? || !vars['last'].nil?) + raise(Mailgun::ParameterError, "Must specify at most one of full_name or first/last. Vars passed: #{vars}") end if vars['full_name'] @@ -448,6 +459,7 @@ def parse_address(address, vars) end return "'#{full_name}' <#{address}>" if full_name + address end @@ -461,24 +473,24 @@ def parse_address(address, vars) # Returns nothing def add_file(disposition, filedata, filename) attachment = File.open(filedata, 'r') if filedata.is_a?(String) - attachment = filedata.dup unless attachment + attachment ||= filedata.dup - fail(Mailgun::ParameterError, - 'Unable to access attachment file object.' - ) unless attachment.respond_to?(:read) + unless attachment.respond_to?(:read) + raise(Mailgun::ParameterError, + 'Unable to access attachment file object.') + end if attachment.respond_to?(:path) && !attachment.respond_to?(:content_type) mime_types = MiniMime.lookup_by_filename(attachment.path) content_type = mime_types.nil? ? 'application/octet-stream' : mime_types.content_type - attachment.instance_eval "def content_type; '#{content_type}'; end" + attachment.instance_eval "def content_type; '#{content_type}'; end", __FILE__, __LINE__ end unless filename.nil? attachment.instance_variable_set :@original_filename, filename - attachment.instance_eval 'def original_filename; @original_filename; end' + attachment.instance_eval 'def original_filename; @original_filename; end', __FILE__, __LINE__ end add_faraday_attachment(disposition, attachment, filename) end end - end diff --git a/lib/mailgun/metrics/metrics.rb b/lib/mailgun/metrics/metrics.rb index 5d3b9c55..75483cc5 100644 --- a/lib/mailgun/metrics/metrics.rb +++ b/lib/mailgun/metrics/metrics.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Mailgun # A Mailgun::Metrics object is a simple interface to Mailgun Metrics. # Uses Mailgun @@ -28,8 +30,8 @@ def initialize(client = Mailgun::Client.new(Mailgun.api_key, Mailgun.api_host || # include_aggregates - [Boolean] Include top-level aggregate metrics. # # Returns [Hash] Metrics - def account_metrics(options={}) - @client.post('analytics/metrics', options.to_json, { "Content-Type" => "application/json" }).to_h! + def account_metrics(options = {}) + @client.post('analytics/metrics', options.to_json, { 'Content-Type' => 'application/json' }).to_h! end # Public: Post query to get account usage metrics @@ -52,8 +54,8 @@ def account_metrics(options={}) # include_aggregates - [Boolean] Include top-level aggregate metrics. # # Returns [Hash] Metrics - def account_usage_metrics(options={}) - @client.post('analytics/usage/metrics', options.to_json, { "Content-Type" => "application/json" }).to_h! + def account_usage_metrics(options = {}) + @client.post('analytics/usage/metrics', options.to_json, { 'Content-Type' => 'application/json' }).to_h! end end end diff --git a/lib/mailgun/response.rb b/lib/mailgun/response.rb index 965cc67b..1df484d3 100644 --- a/lib/mailgun/response.rb +++ b/lib/mailgun/response.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Mailgun # A Mailgun::Response object is instantiated for each response generated # by the Client request. The Response object supports deserialization of @@ -13,7 +15,7 @@ class Response ResponseHash = Struct.new(:body, :status) def self.from_hash(h) # Create a "fake" response object with the data passed from h - self.new ResponseHash.new(h[:body], h[:status]) + new ResponseHash.new(h[:body], h[:status]) end def initialize(response) @@ -28,8 +30,8 @@ def initialize(response) def to_h JSON.parse(@body) - rescue => err - raise ParseError.new(err), err + rescue StandardError => e + raise ParseError.new(e), e end # Replace @body with Ruby Hash @@ -37,8 +39,8 @@ def to_h # @return [Hash] A standard Ruby Hash containing the HTTP result. def to_h! @body = JSON.parse(@body) - rescue => err - raise ParseError.new(err), err + rescue StandardError => e + raise ParseError.new(e), e end # Return response as Yaml @@ -46,8 +48,8 @@ def to_h! # @return [String] A string containing response as YAML def to_yaml YAML.dump(to_h) - rescue => err - raise ParseError.new(err), err + rescue StandardError => e + raise ParseError.new(e), e end # Replace @body with YAML @@ -55,8 +57,8 @@ def to_yaml # @return [String] A string containing response as YAML def to_yaml! @body = YAML.dump(to_h) - rescue => err - raise ParseError.new(err), err + rescue StandardError => e + raise ParseError.new(e), e end # Returns true if response status is 2xx diff --git a/lib/mailgun/subaccounts/subaccounts.rb b/lib/mailgun/subaccounts/subaccounts.rb index 8ea36d57..3b76d520 100644 --- a/lib/mailgun/subaccounts/subaccounts.rb +++ b/lib/mailgun/subaccounts/subaccounts.rb @@ -1,5 +1,6 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # A Mailgun::Subaccounts object is a simple CRUD interface to Mailgun Subaccounts. # Uses Mailgun class Subaccounts @@ -22,9 +23,9 @@ def initialize(client = Mailgun::Client.new(Mailgun.api_key, Mailgun.api_host || # # Returns [Array] A list of subaccounts (hash) def list(options = {}) - client.get("accounts/subaccounts", options).to_h! + client.get('accounts/subaccounts', options).to_h! end - alias_method :get_subaccounts, :list + alias get_subaccounts list # Public: Get subaccount information # @@ -35,7 +36,8 @@ def list(options = {}) # # Returns [Hash] Information on the requested subaccount. def info(subaccount_id, options = {}) - fail(ParameterError, 'No Id of subaccount specified', caller) unless subaccount_id + raise(ParameterError, 'No Id of subaccount specified', caller) unless subaccount_id + client.get("accounts/subaccounts/#{subaccount_id}", options).to_h! end @@ -49,8 +51,9 @@ def info(subaccount_id, options = {}) # # Returns [Hash] of created subaccount def create(name, options = {}) - fail(ParameterError, 'No name given to create subaccount', caller) unless name - client.post("accounts/subaccounts", options.merge!(name: name)).to_h! + raise(ParameterError, 'No name given to create subaccount', caller) unless name + + client.post('accounts/subaccounts', options.merge!(name: name)).to_h! end # Public: Disable a subaccount @@ -62,7 +65,8 @@ def create(name, options = {}) # # Returns [Hash] Information on the requested subaccount. def disable(subaccount_id, options = {}) - fail(ParameterError, 'No Id of subaccount specified', caller) unless subaccount_id + raise(ParameterError, 'No Id of subaccount specified', caller) unless subaccount_id + client.post("accounts/subaccounts/#{subaccount_id}/disable", options).to_h! end @@ -75,7 +79,8 @@ def disable(subaccount_id, options = {}) # # Returns [Hash] Information on the requested subaccount. def enable(subaccount_id, options = {}) - fail(ParameterError, 'No Id of subaccount specified', caller) unless subaccount_id + raise(ParameterError, 'No Id of subaccount specified', caller) unless subaccount_id + client.post("accounts/subaccounts/#{subaccount_id}/enable", options).to_h! end end diff --git a/lib/mailgun/suppressions.rb b/lib/mailgun/suppressions.rb index e13616d1..22570ea1 100644 --- a/lib/mailgun/suppressions.rb +++ b/lib/mailgun/suppressions.rb @@ -1,9 +1,9 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # The Mailgun::Suppressions object makes it easy to manage "suppressions" # attached to an account. "Suppressions" means bounces, unsubscribes, and complaints. class Suppressions - # @param [Mailgun::Client] client API client to use for requests # @param [String] domain Domain name to use for the suppression endpoints. def initialize(client, domain) @@ -60,12 +60,12 @@ def create_bounce(params = {}) def create_bounces(data) # `data` should be a list of hashes, with each hash containing *at least* an `address` key. split_return = [] - if data.length >= 1000 then - resp, resp_l = create_bounces data[999..-1] + if data.length >= 1000 + resp, resp_l = create_bounces data[999..] split_return.push(resp) split_return.concat(resp_l) data = data[0..998] - elsif data.length == 0 then + elsif data.empty? return nil, [] end @@ -74,25 +74,21 @@ def create_bounces(data) # NOTE: `data` could potentially be very large (1000 elements) so it is # more efficient to pop from data and push into a different array as # opposed to possibly copying the entire array to another array. - while not data.empty? do + until data.empty? bounce = data.pop # Bounces MUST contain a `address` key. - if not bounce.include? :address then - raise Mailgun::ParameterError.new "Bounce MUST include a :address key: #{bounce}" - end + raise Mailgun::ParameterError, "Bounce MUST include a :address key: #{bounce}" unless bounce.include? :address bounce.each do |k, v| # Hash values MUST be strings. - if not v.is_a? String then - bounce[k] = v.to_s - end + bounce[k] = v.to_s unless v.is_a? String end valid.push bounce end - response = @client.post("#{@domain}/bounces", valid.to_json, { "Content-Type" => "application/json" }) - return response, split_return + response = @client.post("#{@domain}/bounces", valid.to_json, { 'Content-Type' => 'application/json' }) + [response, split_return] end def delete_bounce(address) @@ -133,22 +129,22 @@ def create_unsubscribe(params = {}) def create_unsubscribes(data) # `data` should be a list of hashes, with each hash containing *at least* an `address` key. split_return = [] - if data.length >= 1000 then - resp, resp_l = create_unsubscribes data[999..-1] + if data.length >= 1000 + resp, resp_l = create_unsubscribes data[999..] split_return.push(resp) split_return.concat(resp_l) data = data[0..998] - elsif data.length == 0 then + elsif data.empty? return nil, [] end valid = [] # Validate the unsubscribes given - while not data.empty? do + until data.empty? unsubscribe = data.pop # unsubscribes MUST contain a `address` key. - if not unsubscribe.include? :address then - raise Mailgun::ParameterError.new "Unsubscribe MUST include a :address key: #{unsubscribe}" + unless unsubscribe.include? :address + raise Mailgun::ParameterError, "Unsubscribe MUST include a :address key: #{unsubscribe}" end unsubscribe.each do |k, v| @@ -164,11 +160,11 @@ def create_unsubscribes(data) valid.push unsubscribe end - response = @client.post("#{@domain}/unsubscribes", valid.to_json, { "Content-Type" => "application/json" }) - return response, split_return + response = @client.post("#{@domain}/unsubscribes", valid.to_json, { 'Content-Type' => 'application/json' }) + [response, split_return] end - def delete_unsubscribe(address, params = {}) + def delete_unsubscribe(address, _params = {}) @client.delete("#{@domain}/unsubscribes/#{escape_address(address)}") end @@ -202,36 +198,34 @@ def create_complaint(params = {}) def create_complaints(data) # `data` should be a list of hashes, with each hash containing *at least* an `address` key. split_return = [] - if data.length >= 1000 then - resp, resp_l = create_complaints data[999..-1] + if data.length >= 1000 + resp, resp_l = create_complaints data[999..] split_return.push(resp) split_return.concat(resp_l) data = data[0..998] - elsif data.length == 0 then + elsif data.empty? return nil, [] end valid = [] # Validate the complaints given - while not data.empty? do + until data.empty? complaint = data.pop # complaints MUST contain a `address` key. - if not complaint.include? :address then - raise Mailgun::ParameterError.new "Complaint MUST include a :address key: #{complaint}" + unless complaint.include? :address + raise Mailgun::ParameterError, "Complaint MUST include a :address key: #{complaint}" end complaint.each do |k, v| # Hash values MUST be strings. - if not v.is_a? String then - complaint[k] = v.to_s - end + complaint[k] = v.to_s unless v.is_a? String end valid.push complaint end - response = @client.post("#{@domain}/complaints", valid.to_json, { "Content-Type" => "application/json" }) - return response, split_return + response = @client.post("#{@domain}/complaints", valid.to_json, { 'Content-Type' => 'application/json' }) + [response, split_return] end def delete_complaint(address) @@ -250,24 +244,23 @@ def get_from_paging(uri, params = {}) def extract_paging(response) rhash = response.to_h - return nil unless rhash.include? "paging" + return nil unless rhash.include? 'paging' - page_info = rhash["paging"] + page_info = rhash['paging'] # Build the `next` endpoint - page_next = URI.parse(page_info["next"]) + page_next = URI.parse(page_info['next']) @paging_next = { - :path => page_next.path[/\/v[\d]\/(.+)/, 1], - :params => Hash[URI.decode_www_form page_next.query], + path: page_next.path[%r{/v\d/(.+)}, 1], + params: Hash[URI.decode_www_form page_next.query] } # Build the `prev` endpoint - page_prev = URI.parse(page_info["previous"]) + page_prev = URI.parse(page_info['previous']) @paging_prev = { - :path => page_prev.path[/\/v[\d]\/(.+)/, 1], - :params => Hash[URI.decode_www_form page_prev.query], + path: page_prev.path[%r{/v\d/(.+)}, 1], + params: Hash[URI.decode_www_form page_prev.query] } end - end end diff --git a/lib/mailgun/tags/analytics_tags.rb b/lib/mailgun/tags/analytics_tags.rb index 323afd2b..6959564f 100644 --- a/lib/mailgun/tags/analytics_tags.rb +++ b/lib/mailgun/tags/analytics_tags.rb @@ -1,5 +1,6 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # A Mailgun::AnalyticsTags object is a simple CRUD interface to Mailgun Tags. # Uses Mailgun class AnalyticsTags @@ -18,7 +19,8 @@ def initialize(client = Mailgun::Client.new(Mailgun.api_key, Mailgun.api_host || # # Returns [Boolean] true or false def update(tag, description) - @client.put('analytics/tags', { tag: tag, description: description }.to_json, { "Content-Type" => "application/json" } ).to_h['message'] == 'Tag updated' + @client.put('analytics/tags', { tag: tag, description: description }.to_json, + { 'Content-Type' => 'application/json' }).to_h['message'] == 'Tag updated' end # Public: Post query to list account tags or search for single tag diff --git a/lib/mailgun/tags/tags.rb b/lib/mailgun/tags/tags.rb index 9bd03cdb..efcf1b11 100644 --- a/lib/mailgun/tags/tags.rb +++ b/lib/mailgun/tags/tags.rb @@ -1,9 +1,9 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # A Mailgun::Tags object is a simple CRUD interface to Mailgun Tags. # Uses Mailgun class Tags - # Public: creates a new Mailgun::Tags instance. # Defaults to Mailgun::Client def initialize(client = Mailgun::Client.new) @@ -22,7 +22,8 @@ def initialize(client = Mailgun::Client.new) # Returns [Array] A list of tags (hash) def get_tags(domain, options = {}) warn('This API is deprecated in favor of our new analytics Tags API') - fail(ParameterError, 'No domain given to store template on', caller) unless domain + raise(ParameterError, 'No domain given to store template on', caller) unless domain + @client.get("#{domain}/tags", options).to_h['items'] end @@ -34,8 +35,9 @@ def get_tags(domain, options = {}) # Returns [Hash] Information on the requested tag. def get_tag(domain, tag) warn('This API is deprecated in favor of our new analytics Tags API') - fail(ParameterError, 'No domain given to find on Mailgun', caller) unless domain - fail(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + raise(ParameterError, 'No domain given to find on Mailgun', caller) unless domain + raise(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + @client.get("#{domain}/tags/#{tag}").to_h! end @@ -49,8 +51,9 @@ def get_tag(domain, tag) # Returns [Boolean] if successful or not def update(domain, tag, options = {}) warn('This API is deprecated in favor of our new analytics Tags API') - fail(ParameterError, 'No domain given to find on Mailgun', caller) unless domain - fail(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + raise(ParameterError, 'No domain given to find on Mailgun', caller) unless domain + raise(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + @client.put("#{domain}/tags/#{tag}", options).to_h['message'] == 'Tag updated' end @@ -68,8 +71,9 @@ def update(domain, tag, options = {}) # Returns [Hash] of tag stats info def get_tag_stats(domain, tag, options = {}) warn('This API is deprecated in favor of our new analytics Tags API') - fail(ParameterError, 'No domain given to find on Mailgun', caller) unless domain - fail(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + raise(ParameterError, 'No domain given to find on Mailgun', caller) unless domain + raise(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + @client.get("#{domain}/tags/#{tag}/stats", options).to_h end @@ -82,8 +86,9 @@ def get_tag_stats(domain, tag, options = {}) # Returns [Boolean] if successful or not def remove(domain, tag) warn('This API is deprecated in favor of our new analytics Tags API') - fail(ParameterError, 'No domain given to remove on Mailgun', caller) unless domain - fail(ParameterError, 'No template name given to find on provided domain', caller) unless tag + raise(ParameterError, 'No domain given to remove on Mailgun', caller) unless domain + raise(ParameterError, 'No template name given to find on provided domain', caller) unless tag + @client.delete("#{domain}/tags/#{tag}").to_h['message'] == 'Tag deleted' end @@ -95,8 +100,9 @@ def remove(domain, tag) # Returns [Hash] of countries of origin for a given domain def get_countries_aggregated_stats(domain, tag) warn('This API is deprecated in favor of our new analytics Tags API') - fail(ParameterError, 'No domain given to find on Mailgun', caller) unless domain - fail(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + raise(ParameterError, 'No domain given to find on Mailgun', caller) unless domain + raise(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + @client.get("#{domain}/tags/#{tag}/stats/aggregates/countries").to_h end @@ -108,8 +114,9 @@ def get_countries_aggregated_stats(domain, tag) # Returns [Hash] of email providers for a given domain def get_providers_aggregated_stats(domain, tag) warn('This API is deprecated in favor of our new analytics Tags API') - fail(ParameterError, 'No domain given to find on Mailgun', caller) unless domain - fail(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + raise(ParameterError, 'No domain given to find on Mailgun', caller) unless domain + raise(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + @client.get("#{domain}/tags/#{tag}/stats/aggregates/providers").to_h end @@ -121,8 +128,9 @@ def get_providers_aggregated_stats(domain, tag) # Returns [Hash] of devices for a given domain def get_devices_aggregated_stats(domain, tag) warn('This API is deprecated in favor of our new analytics Tags API') - fail(ParameterError, 'No domain given to find on Mailgun', caller) unless domain - fail(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + raise(ParameterError, 'No domain given to find on Mailgun', caller) unless domain + raise(ParameterError, 'No tag name given to find on provided domain', caller) unless tag + @client.get("#{domain}/tags/#{tag}/stats/aggregates/devices").to_h end end diff --git a/lib/mailgun/templates/templates.rb b/lib/mailgun/templates/templates.rb index 2b5e50ab..af39f45a 100644 --- a/lib/mailgun/templates/templates.rb +++ b/lib/mailgun/templates/templates.rb @@ -1,9 +1,9 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # A Mailgun::Templates object is a simple CRUD interface to Mailgun Templates. # Uses Mailgun class Templates - # Public: creates a new Mailgun::Templates instance. # Defaults to Mailgun::Client def initialize(client = Mailgun::Client.new) @@ -24,7 +24,8 @@ def initialize(client = Mailgun::Client.new) # # Returns [Hash] of created template def create(domain, options = {}) - fail(ParameterError, 'No domain given to store template on', caller) unless domain + raise(ParameterError, 'No domain given to store template on', caller) unless domain + @client.post("#{domain}/templates", options).to_h end @@ -38,8 +39,9 @@ def create(domain, options = {}) # # Returns [Hash] Information on the requested template. def info(domain, template_name, options = {}) - fail(ParameterError, 'No domain given to find on Mailgun', caller) unless domain - fail(ParameterError, 'No template name given to find on provided domain', caller) unless template_name + raise(ParameterError, 'No domain given to find on Mailgun', caller) unless domain + raise(ParameterError, 'No template name given to find on provided domain', caller) unless template_name + @client.get("#{domain}/templates/#{template_name}", options).to_h! end @@ -52,8 +54,9 @@ def info(domain, template_name, options = {}) # # Returns [Hash] of updated domain def update(domain, template_name, options = {}) - fail(ParameterError, 'No domain given to add on Mailgun', caller) unless domain - fail(ParameterError, 'No template name given to find on provided domain', caller) unless template_name + raise(ParameterError, 'No domain given to add on Mailgun', caller) unless domain + raise(ParameterError, 'No template name given to find on provided domain', caller) unless template_name + @client.put("#{domain}/templates/#{template_name}", options).to_h end @@ -65,12 +68,13 @@ def update(domain, template_name, options = {}) # # Returns [Boolean] if successful or not def remove(domain, template_name) - fail(ParameterError, 'No domain given to remove on Mailgun', caller) unless domain - fail(ParameterError, 'No template name given to find on provided domain', caller) unless template_name + raise(ParameterError, 'No domain given to remove on Mailgun', caller) unless domain + raise(ParameterError, 'No template name given to find on provided domain', caller) unless template_name + @client.delete("#{domain}/templates/#{template_name}").to_h['message'] == 'template has been deleted' end - alias_method :delete, :remove - alias_method :delete_template, :remove + alias delete remove + alias delete_template remove # Public: Get Templates # @@ -81,10 +85,11 @@ def remove(domain, template_name) # # Returns [Array] A list of templates (hash) def list(domain, options = {}) - fail(ParameterError, 'No domain given.', caller) unless domain + raise(ParameterError, 'No domain given.', caller) unless domain + @client.get("#{domain}/templates", options).to_h['items'] end - alias_method :get_templates, :list + alias get_templates list # Public: Delete Templates # NOTE: This method deletes all stored templates for the domain. @@ -93,10 +98,11 @@ def list(domain, options = {}) # # Returns [Boolean] if successful or not def remove_all(domain) - fail(ParameterError, 'No domain given to remove on Mailgun', caller) unless domain + raise(ParameterError, 'No domain given to remove on Mailgun', caller) unless domain + @client.delete("#{domain}/templates").to_h['message'] == 'templates have been deleted' end - alias_method :delete_templates, :remove_all + alias delete_templates remove_all # Public: Create a new version of a template # @@ -112,8 +118,9 @@ def remove_all(domain) # # Returns [Hash] of updated template def create_version(domain, template_name, options = {}) - fail(ParameterError, 'No domain given.', caller) unless domain - fail(ParameterError, 'No template name given.', caller) unless template_name + raise(ParameterError, 'No domain given.', caller) unless domain + raise(ParameterError, 'No template name given.', caller) unless template_name + @client.post("#{domain}/templates/#{template_name}/versions", options).to_h end @@ -125,9 +132,10 @@ def create_version(domain, template_name, options = {}) # # Returns [Hash] Information on the requested template + version. def info_version(domain, template_name, tag) - fail(ParameterError, 'No domain given to find on Mailgun', caller) unless domain - fail(ParameterError, 'No template name given to find on provided domain', caller) unless template_name - fail(ParameterError, 'No version tag given.', caller) unless tag + raise(ParameterError, 'No domain given to find on Mailgun', caller) unless domain + raise(ParameterError, 'No template name given to find on provided domain', caller) unless template_name + raise(ParameterError, 'No version tag given.', caller) unless tag + @client.get("#{domain}/templates/#{template_name}/versions/#{tag}").to_h! end @@ -145,9 +153,10 @@ def info_version(domain, template_name, tag) # # Returns [Hash] of updated template's version def update_version(domain, template_name, tag, options = {}) - fail(ParameterError, 'No domain given.', caller) unless domain - fail(ParameterError, 'No template name given to find on provided domain.', caller) unless template_name - fail(ParameterError, 'No version tag given.', caller) unless tag + raise(ParameterError, 'No domain given.', caller) unless domain + raise(ParameterError, 'No template name given to find on provided domain.', caller) unless template_name + raise(ParameterError, 'No version tag given.', caller) unless tag + @client.put("#{domain}/templates/#{template_name}/versions/#{tag}", options).to_h end @@ -159,11 +168,12 @@ def update_version(domain, template_name, tag, options = {}) # # Returns [Boolean] if successful or not def delete_version(domain, template_name, tag) - fail(ParameterError, 'No domain given.', caller) unless domain - fail(ParameterError, 'No template name given to find on provided domain.', caller) unless template_name - fail(ParameterError, 'No version tag given.', caller) unless tag + raise(ParameterError, 'No domain given.', caller) unless domain + raise(ParameterError, 'No template name given to find on provided domain.', caller) unless template_name + raise(ParameterError, 'No version tag given.', caller) unless tag + @client.delete("#{domain}/templates/#{template_name}/versions/#{tag}") - .to_h['message'] == 'version has been deleted' + .to_h['message'] == 'version has been deleted' end # Public: Get Template's Versions list @@ -177,8 +187,9 @@ def delete_version(domain, template_name, tag) # # Returns [Array] A list of template's versions (hash) def template_versions_list(domain, template_name, options = {}) - fail(ParameterError, 'No domain given.', caller) unless domain - fail(ParameterError, 'No template name given to find on provided domain.', caller) unless template_name + raise(ParameterError, 'No domain given.', caller) unless domain + raise(ParameterError, 'No template name given to find on provided domain.', caller) unless template_name + @client.get("#{domain}/templates/#{template_name}/versions", options).to_h end end diff --git a/lib/mailgun/version.rb b/lib/mailgun/version.rb index 56813e51..4f65b58b 100644 --- a/lib/mailgun/version.rb +++ b/lib/mailgun/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # It's the version. Yeay! module Mailgun VERSION = '1.4.1' diff --git a/lib/mailgun/webhooks/webhooks.rb b/lib/mailgun/webhooks/webhooks.rb index 2216cc68..637adac4 100644 --- a/lib/mailgun/webhooks/webhooks.rb +++ b/lib/mailgun/webhooks/webhooks.rb @@ -1,9 +1,10 @@ -module Mailgun +# frozen_string_literal: true +module Mailgun # A Mailgun::Webhooks object is a simple CRUD interface to Mailgun Webhooks. # Uses Mailgun class Webhooks - ACTIONS = %w(accepted clicked complained delivered opened permanent_fail temporary_fail unsubscribed).freeze + ACTIONS = %w[accepted clicked complained delivered opened permanent_fail temporary_fail unsubscribed].freeze # Public creates a new Mailgun::Webhooks instance. # Defaults to Mailgun::Client @@ -21,7 +22,7 @@ def list(domain, options = {}) res = @client.get("domains/#{domain}/webhooks", options) res.to_h['webhooks'] end - alias_method :get_webhooks, :list + alias get_webhooks list # Public: Get webook information for a specific action # @@ -36,7 +37,7 @@ def info(domain, action) rescue NoMethodError '' end - alias_method :get_webhook_url, :info + alias get_webhook_url info # Public: Add webhook # @@ -49,8 +50,8 @@ def create(domain, action, url = '') res = @client.post("domains/#{domain}/webhooks", id: action, url: url) res.to_h['webhook']['urls'].include?(url) && res.to_h['message'] == 'Webhook has been created' end - alias_method :add, :create - alias_method :add_webhook, :create + alias add create + alias add_webhook create # Public: Sets all webhooks to the same URL # @@ -63,10 +64,10 @@ def create_all(domain, url = '') add_webhook domain, action, url end true - rescue + rescue StandardError false end - alias_method :add_all_webhooks, :create_all + alias add_all_webhooks create_all # Public: Update webhook # @@ -76,12 +77,13 @@ def create_all(domain, url = '') # # Returns a Boolean of whether the webhook was updated def update(domain, action, url = '') - fail Mailgun::ParameterError('Domain not provided to update webhooks') unless domain - fail Mailgun::ParameterError('Action not provided to identify webhook to update') unless action + raise Mailgun::ParameterError('Domain not provided to update webhooks') unless domain + raise Mailgun::ParameterError('Action not provided to identify webhook to update') unless action + res = @client.put("domains/#{domain}/webhooks/#{action}", id: action, url: url) res.to_h['webhook']['urls'] == url && res.to_h['message'] == 'Webhook has been updated' end - alias_method :update_webhook, :update + alias update_webhook update # Public: Delete a specific webhook # @@ -90,14 +92,15 @@ def update(domain, action, url = '') # # Returns a Boolean of the success def remove(domain, action) - fail Mailgun::ParameterError('Domain not provided to remove webhook from') unless domain - fail Mailgun::ParameterError('Action not provided to identify webhook to remove') unless action + raise Mailgun::ParameterError('Domain not provided to remove webhook from') unless domain + raise Mailgun::ParameterError('Action not provided to identify webhook to remove') unless action + @client.delete("domains/#{domain}/webhooks/#{action}").to_h['message'] == 'Webhook has been deleted' rescue Mailgun::CommunicationError false end - alias_method :delete, :remove - alias_method :delete_webhook, :remove + alias delete remove + alias delete_webhook remove # Public: Delete all webhooks for a domain # @@ -105,13 +108,13 @@ def remove(domain, action) # # Returns a Boolean on the success def remove_all(domain) - fail Mailgun::ParameterError('Domain not provided to remove webhooks from') unless domain + raise Mailgun::ParameterError('Domain not provided to remove webhooks from') unless domain + ACTIONS.each do |action| delete_webhook domain, action end end - alias_method :delete_all, :remove_all - alias_method :delete_all_webooks, :remove_all - + alias delete_all remove_all + alias delete_all_webooks remove_all end end diff --git a/lib/railgun.rb b/lib/railgun.rb index 800e6fbb..ae4129d3 100644 --- a/lib/railgun.rb +++ b/lib/railgun.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # require ruby dependencies require 'json' diff --git a/lib/railgun/attachment.rb b/lib/railgun/attachment.rb index 38a13377..7ede73e3 100644 --- a/lib/railgun/attachment.rb +++ b/lib/railgun/attachment.rb @@ -1,7 +1,7 @@ -module Railgun +# frozen_string_literal: true +module Railgun class Attachment < StringIO - attr_reader :filename, :content_type, :path, :original_filename, :overwritten_filename @@ -9,17 +9,15 @@ def initialize(attachment, *args) @path = '' @inline = args.detect { |opt| opt[:inline] } - if @inline - @filename = attachment.cid - else - @filename = attachment.filename - end + @filename = if @inline + attachment.cid + else + attachment.filename + end @original_filename = @filename - if args.detect { |opt| opt[:filename] } - @filename = opt[:filename] - end + @filename = opt[:filename] if args.detect { |opt| opt[:filename] } @overwritten_filename = @filename @@ -41,9 +39,7 @@ def source_filename end def attach_to_message!(mb) - if mb.nil? - nil - end + nil if mb.nil? if inline? mb.add_inline_image self, @filename @@ -51,6 +47,5 @@ def attach_to_message!(mb) mb.add_attachment self, @filename end end - end end diff --git a/lib/railgun/errors.rb b/lib/railgun/errors.rb index 96d7521a..849f7fc3 100644 --- a/lib/railgun/errors.rb +++ b/lib/railgun/errors.rb @@ -1,7 +1,7 @@ -module Railgun +# frozen_string_literal: true +module Railgun class Error < StandardError - attr_reader :object def initialize(message = nil, object = nil) @@ -15,7 +15,6 @@ class ConfigurationError < Error end class InternalError < Error - attr_reader :source_exception def initialize(source_exc, message = nil, object = nil) diff --git a/lib/railgun/mailer.rb b/lib/railgun/mailer.rb index 4cb199d2..52238272 100644 --- a/lib/railgun/mailer.rb +++ b/lib/railgun/mailer.rb @@ -1,11 +1,11 @@ -module Railgun +# frozen_string_literal: true +module Railgun # Railgun::Mailer is an ActionMailer provider for sending mail through # Mailgun. class Mailer - # List of the headers that will be ignored when copying headers from `mail.header_fields` - IGNORED_HEADERS = %w[ to from subject reply-to mime-version template ] + IGNORED_HEADERS = %w[to from subject reply-to mime-version template].freeze # [Hash] config -> # Requires *at least* `api_key` and `domain` keys. @@ -17,15 +17,15 @@ class Mailer def initialize(config) @config = config - [:api_key, :domain].each do |k| - raise Railgun::ConfigurationError.new("Config requires `#{k}` key", @config) unless @config.has_key?(k) + %i[api_key domain].each do |k| + raise Railgun::ConfigurationError.new("Config requires `#{k}` key", @config) unless @config.key?(k) end @mg_client = Mailgun::Client.new( config[:api_key], config[:api_host] || 'api.mailgun.net', config[:api_version] || 'v3', - config[:api_ssl].nil? ? true : config[:api_ssl], + config[:api_ssl].nil? || config[:api_ssl], false, config[:timeout] ) @@ -34,10 +34,10 @@ def initialize(config) # To avoid exception in mail gem v2.6 @settings = { return_response: true } - if (@config[:fake_message_send] || false) - Rails.logger.info "NOTE: fake message sending has been enabled for mailgun-ruby!" - @mg_client.enable_test_mode! - end + return unless @config[:fake_message_send] || false + + Rails.logger.info 'NOTE: fake message sending has been enabled for mailgun-ruby!' + @mg_client.enable_test_mode! end def deliver!(mail) @@ -52,7 +52,7 @@ def deliver!(mail) mg_message = Railgun.transform_for_mailgun(mail) response = @mg_client.send_message(@mg_domain, mg_message) - if response.code == 200 then + if response.code == 200 mg_id = response.to_h['id'] mail.message_id = mg_id end @@ -68,9 +68,9 @@ def mailgun_client # Set @mg_domain from mail[:domain] header if present, then remove it to prevent being sent. def set_mg_domain(mail) return mail[:domain].value if mail[:domain] + domain end - end module_function @@ -102,7 +102,7 @@ def transform_for_mailgun(mail) # note: this will filter out parameters such as `from`, `to`, and so forth # as they are accepted as POST parameters on the message endpoint. - msg_headers = Hash.new + msg_headers = {} # h:* attributes (headers) @@ -111,11 +111,11 @@ def transform_for_mailgun(mail) mail.headers(mail.mailgun_headers || {}) mail.header_fields.each do |field| header = field.name.downcase - if msg_headers.include? header - msg_headers[header] = [msg_headers[header], field.value].flatten - else - msg_headers[header] = field.value - end + msg_headers[header] = if msg_headers.include? header + [msg_headers[header], field.value].flatten + else + field.value + end end msg_headers.each do |k, v| @@ -140,7 +140,7 @@ def transform_for_mailgun(mail) message['recipient-variables'] = mail.mailgun_recipient_variables.to_json if mail.mailgun_recipient_variables # reject blank values - message.delete_if do |k, v| + message.delete_if do |_k, v| next true if v.nil? # if it's an array remove empty elements @@ -149,7 +149,7 @@ def transform_for_mailgun(mail) v.respond_to?(:empty?) && v.empty? end - return message + message end # Acts on a Rails/ActionMailer message object and uses Mailgun::MessageBuilder @@ -169,7 +169,7 @@ def build_message_object(mail) mb.body_text extract_body_text(mail) mb.amp_html extract_amp_html(mail) - [:to, :cc, :bcc].each do |rcpt_type| + %i[to cc bcc].each do |rcpt_type| addrs = mail[rcpt_type] || nil case addrs when String @@ -196,7 +196,7 @@ def build_message_object(mail) attach.attach_to_message! mb end - return mb.message + mb.message end # Returns the decoded HTML body from the Mail::Message object if available, @@ -206,11 +206,9 @@ def build_message_object(mail) # # @return [String] def extract_body_html(mail) - begin - retrieve_html_part(mail).body.decoded || nil - rescue - nil - end + retrieve_html_part(mail).body.decoded || nil + rescue StandardError + nil end # Returns the decoded text body from the Mail::Message object if it is available, @@ -220,11 +218,9 @@ def extract_body_html(mail) # # @return [String] def extract_body_text(mail) - begin - retrieve_text_part(mail).body.decoded || nil - rescue - nil - end + retrieve_text_part(mail).body.decoded || nil + rescue StandardError + nil end # Returns the decoded AMP HTML from the Mail::Message object if it is available, @@ -234,11 +230,9 @@ def extract_body_text(mail) # # @return [String] def extract_amp_html(mail) - begin - retrieve_amp_part(mail).body.decoded || nil - rescue - nil - end + retrieve_amp_part(mail).body.decoded || nil + rescue StandardError + nil end # Returns the mail object from the Mail::Message object if text part exists, @@ -250,7 +244,8 @@ def extract_amp_html(mail) # @return [Mail::Message] mail message with its content-type = text/plain def retrieve_text_part(mail) return mail.text_part if mail.multipart? - (mail.mime_type =~ /^text\/plain$/i) && mail + + (mail.mime_type =~ %r{^text/plain$}i) && mail end # Returns the mail object from the Mail::Message object if html part exists, @@ -262,7 +257,8 @@ def retrieve_text_part(mail) # @return [Mail::Message] mail message with its content-type = text/html def retrieve_html_part(mail) return mail.html_part if mail.multipart? - (mail.mime_type =~ /^text\/html$/i) && mail + + (mail.mime_type =~ %r{^text/html$}i) && mail end # Returns the mail object from the Mail::Message object if AMP part exists, diff --git a/lib/railgun/railtie.rb b/lib/railgun/railtie.rb index 0c308f73..c4cf0717 100644 --- a/lib/railgun/railtie.rb +++ b/lib/railgun/railtie.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Railgun class Railtie < ::Rails::Railtie ActiveSupport.on_load(:action_mailer) do diff --git a/mailgun.gemspec b/mailgun.gemspec index 93aea6df..f619ab29 100644 --- a/mailgun.gemspec +++ b/mailgun.gemspec @@ -1,10 +1,10 @@ -# coding: utf-8 -lib = File.expand_path('../lib', __FILE__) +# frozen_string_literal: true + +lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'mailgun/version' Gem::Specification.new do |spec| - spec.name = 'mailgun-ruby' spec.version = Mailgun::VERSION spec.homepage = 'https://www.mailgun.com/' @@ -23,21 +23,22 @@ Gem::Specification.new do |spec| spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) - spec.require_paths = ["lib"] + spec.require_paths = ['lib'] spec.required_ruby_version = '>= 3.0.0' spec.add_development_dependency 'bundler', '>= 1.16.2' + spec.add_development_dependency 'pry', '~> 0.16.0' + spec.add_development_dependency 'rails' + spec.add_development_dependency 'rake', '~> 13.3.1' spec.add_development_dependency 'rspec', '~> 3.13.0' spec.add_development_dependency 'rspec-its', '~> 2.0.0' - spec.add_development_dependency 'rake', '~> 13.3.1' - spec.add_development_dependency 'webmock', '~> 3.7' - spec.add_development_dependency 'pry', '~> 0.16.0' - spec.add_development_dependency 'vcr', '~> 6.4.0' + spec.add_development_dependency 'rubocop' spec.add_development_dependency 'simplecov', '~> 0.16.1' - spec.add_development_dependency 'rails' - spec.add_dependency 'mini_mime' - spec.add_dependency 'faraday', "~> 2.1" + spec.add_development_dependency 'vcr', '~> 6.4.0' + spec.add_development_dependency 'webmock', '~> 3.7' + spec.add_dependency 'faraday', '~> 2.1' spec.add_dependency 'faraday-multipart', '< 2' + spec.add_dependency 'mini_mime' spec.add_dependency 'zeitwerk' end diff --git a/spec/integration/analytics_tags_spec.rb b/spec/integration/analytics_tags_spec.rb index f8d2e62f..a186ffb0 100644 --- a/spec/integration/analytics_tags_spec.rb +++ b/spec/integration/analytics_tags_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' @@ -20,13 +22,14 @@ describe '#list' do it 'returns a list of tags' do response = mg_obj.list( - { - pagination: { - sort: 'lastseen:desc', - limit: 10 - }, - include_subaccounts: true - }) + { + pagination: { + sort: 'lastseen:desc', + limit: 10 + }, + include_subaccounts: true + } + ) expect(response[0]['account_id']).to eq('test') expect(response[0]['tag']).to eq('test1') @@ -45,7 +48,7 @@ it 'returns limits' do response = mg_obj.limits - expect(response['limit']).to eq(100000) + expect(response['limit']).to eq(100_000) end end end diff --git a/spec/integration/bounces_spec.rb b/spec/integration/bounces_spec.rb index 3bd22a9c..7e238139 100644 --- a/spec/integration/bounces_spec.rb +++ b/spec/integration/bounces_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "bounces" } +vcr_opts = { cassette_name: 'bounces' } describe 'For the Bounces endpoint', order: :defined, vcr: vcr_opts do before(:all) do @@ -12,33 +14,32 @@ it 'creates a bounce' do @result = @mg_obj.post("#{@domain}/bounces", - {:address => @email, - :code => 550, - :error => "Integration Test"}) + { address: @email, + code: 550, + error: 'Integration Test' }) @result.to_h! - expect(@result.body["message"]).to eq("Address has been added to the bounces table") - expect(@result.body["address"]).to eq(@email) + expect(@result.body['message']).to eq('Address has been added to the bounces table') + expect(@result.body['address']).to eq(@email) end it 'get a bounce.' do result = @mg_obj.get("#{@domain}/bounces/#{CGI.escape(@email)}") result.to_h! - expect(result.body["code"]).to eq("550") - expect(result.body["address"]).to eq(@email) - expect(result.body["error"]).to eq("Integration Test") + expect(result.body['code']).to eq('550') + expect(result.body['address']).to eq(@email) + expect(result.body['error']).to eq('Integration Test') end it 'gets a list of bounces.' do result = @mg_obj.get("#{@domain}/bounces") result.to_h! - expect(result.body["items"].length).to be > 0 + expect(result.body['items'].length).to be > 0 end it 'deletes a bounce' do @mg_obj.delete("#{@domain}/bounces/#{CGI.escape(@email)}") end - end diff --git a/spec/integration/campaign_spec.rb b/spec/integration/campaign_spec.rb index ac28d00c..9919769b 100644 --- a/spec/integration/campaign_spec.rb +++ b/spec/integration/campaign_spec.rb @@ -1,57 +1,59 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "campaigns" } +vcr_opts = { cassette_name: 'campaigns' } describe 'For the campaigns endpoint', vcr: vcr_opts do before(:all) do skip 'pending removal' @mg_obj = Mailgun::Client.new(APIKEY, APIHOST, APIVERSION, SSL) @domain = TESTDOMAIN - @campaign_id = "integration_test_campaign" + @campaign_id = 'integration_test_campaign' end it 'creates a campaign' do - result = @mg_obj.post("#{@domain}/campaigns", {:name => 'My Campaign', - :id => @campaign_id}) + result = @mg_obj.post("#{@domain}/campaigns", { name: 'My Campaign', + id: @campaign_id }) result.to_h! - expect(result.body["message"]).to eq("Campaign created") - expect(result.body["campaign"]["id"]).to eq(@campaign_id) - expect(result.body["campaign"]["name"]).to eq('My Campaign') + expect(result.body['message']).to eq('Campaign created') + expect(result.body['campaign']['id']).to eq(@campaign_id) + expect(result.body['campaign']['name']).to eq('My Campaign') end it 'get a campaign.' do result = @mg_obj.get("#{@domain}/campaigns/#{@campaign_id}") result.to_h! - expect(result.body["id"]).to eq(@campaign_id) - expect(result.body["name"]).to eq('My Campaign') + expect(result.body['id']).to eq(@campaign_id) + expect(result.body['name']).to eq('My Campaign') end it 'gets a list of all campaigns.' do - result = @mg_obj.get("#{@domain}/campaigns", {:limit => 50}) + result = @mg_obj.get("#{@domain}/campaigns", { limit: 50 }) result.to_h! - expect(result.body["total_count"]).to be > 0 + expect(result.body['total_count']).to be > 0 end it 'update a campaign.' do - result = @mg_obj.put("#{@domain}/campaigns/#{@campaign_id}", {:name => 'My Updated Campaign', - :id => @campaign_id}) + result = @mg_obj.put("#{@domain}/campaigns/#{@campaign_id}", { name: 'My Updated Campaign', + id: @campaign_id }) result.to_h! - expect(result.body["message"]).to eq("Campaign updated") - expect(result.body["campaign"]["id"]).to eq(@campaign_id) - expect(result.body["campaign"]["name"]).to eq('My Updated Campaign') + expect(result.body['message']).to eq('Campaign updated') + expect(result.body['campaign']['id']).to eq(@campaign_id) + expect(result.body['campaign']['name']).to eq('My Updated Campaign') end it 'get campaign events.' do - expect{@mg_obj.get("#{@domain}/campaigns/#{@campaign_id}/events", {:groupby => "clicked"})}.not_to raise_error + expect { @mg_obj.get("#{@domain}/campaigns/#{@campaign_id}/events", { groupby: 'clicked' }) }.not_to raise_error end it 'get campaign stats.' do - expect{@mg_obj.get("#{@domain}/campaigns/#{@campaign_id}/stats", {:groupby => "domain"})}.not_to raise_error + expect { @mg_obj.get("#{@domain}/campaigns/#{@campaign_id}/stats", { groupby: 'domain' }) }.not_to raise_error end it 'removes a campaign' do diff --git a/spec/integration/complaints_spec.rb b/spec/integration/complaints_spec.rb index 5a020783..25229ecd 100644 --- a/spec/integration/complaints_spec.rb +++ b/spec/integration/complaints_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "complaints" } +vcr_opts = { cassette_name: 'complaints' } describe 'For the Complaints endpoint', order: :defined, vcr: vcr_opts do before(:all) do @@ -11,25 +13,25 @@ end it 'creates a complaint' do - @result = @mg_obj.post("#{@domain}/complaints", {:address => @email}) + @result = @mg_obj.post("#{@domain}/complaints", { address: @email }) @result.to_h! - expect(@result.body["message"]).to eq("Address has been added to the complaints table") - expect(@result.body["address"]).to eq(@email) + expect(@result.body['message']).to eq('Address has been added to the complaints table') + expect(@result.body['address']).to eq(@email) end it 'get a complaint.' do result = @mg_obj.get("#{@domain}/complaints/#{@email}") result.to_h! - expect(result.body["address"]).to eq(@email) + expect(result.body['address']).to eq(@email) end it 'gets a list of complaints.' do result = @mg_obj.get("#{@domain}/complaints") result.to_h! - expect(result.body["items"].length).to be > 0 + expect(result.body['items'].length).to be > 0 end it 'removes a complaint' do diff --git a/spec/integration/domains_spec.rb b/spec/integration/domains_spec.rb index 02597593..d325cd6a 100644 --- a/spec/integration/domains_spec.rb +++ b/spec/integration/domains_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "domains" } +vcr_opts = { cassette_name: 'domains' } describe 'For the domains endpoint', vcr: vcr_opts do let(:api_version) { APIVERSION } @@ -71,7 +73,6 @@ end end - context 'Domain::Keys methods' do describe '#list_domain_keys' do let(:api_version) { 'v1' } @@ -123,7 +124,6 @@ let(:api_version) { 'v4' } it 'activates a domain key' do - result = mg_obj.activate_domain_key( domain, 'mailo1' @@ -187,7 +187,7 @@ end context 'Domain::Tracking methods' do - # TODO add missing: + # TODO: add missing: # get_domain_tracking_certificate # regenerate_domain_tracking_certificate # generate_domain_tracking_certificate @@ -244,7 +244,7 @@ end context 'Domain::DKIM_Security methods' do - # TODO add missing: + # TODO: add missing: # dkim_rotation # dkim_rotate end @@ -261,7 +261,7 @@ } ) - expect(result['message']).to eq("Created 1 credentials pair(s)") + expect(result['message']).to eq('Created 1 credentials pair(s)') end end diff --git a/spec/integration/email_validation_spec.rb b/spec/integration/email_validation_spec.rb index 97cdcc77..ab1ecf97 100644 --- a/spec/integration/email_validation_spec.rb +++ b/spec/integration/email_validation_spec.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' require 'mailgun/address' -vcr_opts = { :cassette_name => "email_validation" } +vcr_opts = { cassette_name: 'email_validation' } describe 'For the email validation endpoint', order: :defined, vcr: vcr_opts do before(:all) do @mg_obj = Mailgun::Address.new - @valid = ["Alice ", "bob@example.com"] - @invalid = ["example.org"] + @valid = ['Alice ', 'bob@example.com'] + @invalid = ['example.org'] @all_addrs = @valid + @invalid end @@ -19,54 +21,53 @@ skip 'is parse method removed?' res = @mg_obj.parse(@all_addrs) - expect(res["parsed"]).to eq(@valid) - expect(res["unparsable"]).to eq(@invalid) + expect(res['parsed']).to eq(@valid) + expect(res['unparsable']).to eq(@invalid) end it 'validates alice@mailgun.net with info' do - res = @mg_obj.validate("alice@mailgun.net") + res = @mg_obj.validate('alice@mailgun.net') expected = { - "address" => "alice@mailgun.net", - "did_you_mean" => nil, - "is_disposable_address" => false, - "is_role_address" => false, - "is_valid" => true, - "mailbox_verification" => "true", - "reason" => nil, - "parts" => { - "display_name" => nil, - "domain" => "mailgun.net", - "local_part" => "alice", - }, + 'address' => 'alice@mailgun.net', + 'did_you_mean' => nil, + 'is_disposable_address' => false, + 'is_role_address' => false, + 'is_valid' => true, + 'mailbox_verification' => 'true', + 'reason' => nil, + 'parts' => { + 'display_name' => nil, + 'domain' => 'mailgun.net', + 'local_part' => 'alice' + } } expect(res).to eq(expected) end it 'performs mailbox validation for alice@mailgun.net' do - res = @mg_obj.validate("alice@mailgun.net", true) + res = @mg_obj.validate('alice@mailgun.net', true) - expect(res["mailbox_verification"]).to eq("true") + expect(res['mailbox_verification']).to eq('true') end it 'fails to validate example.org' do - res = @mg_obj.validate("example.org") + res = @mg_obj.validate('example.org') expected = { - "address" => "example.org", - "did_you_mean" => nil, - "is_disposable_address" => false, - "is_role_address" => false, - "is_valid" => false, - "mailbox_verification" => "unknown", - #"reason" => "Validation failed for 'example.org', reason: 'malformed address; missing @ sign'", - "parts" => { - "display_name" => nil, - "domain" => nil, - "local_part" => nil, - }, + 'address' => 'example.org', + 'did_you_mean' => nil, + 'is_disposable_address' => false, + 'is_role_address' => false, + 'is_valid' => false, + 'mailbox_verification' => 'unknown', + # "reason" => "Validation failed for 'example.org', reason: 'malformed address; missing @ sign'", + 'parts' => { + 'display_name' => nil, + 'domain' => nil, + 'local_part' => nil + } } expect(res).to eq(expected) end - end diff --git a/spec/integration/events_spec.rb b/spec/integration/events_spec.rb index 95532de4..88659712 100644 --- a/spec/integration/events_spec.rb +++ b/spec/integration/events_spec.rb @@ -1,8 +1,10 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' require 'mailgun/events/events' -vcr_opts = { :cassette_name => "events" } +vcr_opts = { cassette_name: 'events' } describe 'For the Events endpoint', vcr: vcr_opts do before(:all) do @@ -12,12 +14,12 @@ end it 'can get an event.' do - result = @mg_obj.get("#{@domain}/events", {:limit => 1}) + result = @mg_obj.get("#{@domain}/events", { limit: 1 }) result.to_h! - expect(result.body["items"].length).to be_within(1).of(1) - expect(result.body["paging"]).to include("next") - expect(result.body["paging"]).to include("previous") + expect(result.body['items'].length).to be_within(1).of(1) + expect(result.body['paging']).to include('next') + expect(result.body['paging']).to include('previous') end it 'can iterate over all events with `each`' do diff --git a/spec/integration/list_members_spec.rb b/spec/integration/list_members_spec.rb index 7ff6ec5f..61020346 100644 --- a/spec/integration/list_members_spec.rb +++ b/spec/integration/list_members_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "list_members" } +vcr_opts = { cassette_name: 'list_members' } describe 'For the Mailing Lists Members endpoint', order: :defined, vcr: vcr_opts do before(:all) do @@ -10,54 +12,53 @@ @ml_address = "integration_test_list@#{@domain}" @ml_member = "integration_test_member_member@#{@domain}" end - + it 'creates a list' do - result = @mg_obj.post("lists", {:address => @ml_address, - :name => 'Integration Test List', - :description => 'This list should be deleted automatically.', - :access_level => 'members'}) + result = @mg_obj.post('lists', { address: @ml_address, + name: 'Integration Test List', + description: 'This list should be deleted automatically.', + access_level: 'members' }) result.to_h! - expect(result.body["message"]).to eq("Mailing list has been created") - expect(result.body["list"]["address"]).to eq(@ml_address) - expect(result.body["list"]["name"]).to eq('Integration Test List') + expect(result.body['message']).to eq('Mailing list has been created') + expect(result.body['list']['address']).to eq(@ml_address) + expect(result.body['list']['name']).to eq('Integration Test List') end it 'adds a list member' do result = @mg_obj.post("lists/#{@ml_address}/members", - {:address => @ml_member, - :name => 'Jane Doe', - :subscribed => true, - :upsert => 'no'}) + { address: @ml_member, + name: 'Jane Doe', + subscribed: true, + upsert: 'no' }) result.to_h! - expect(result.body["message"]).to eq("Mailing list member has been created") - expect(result.body["member"]["address"]).to eq(@ml_member) - expect(result.body["member"]["name"]).to eq('Jane Doe') + expect(result.body['message']).to eq('Mailing list member has been created') + expect(result.body['member']['address']).to eq(@ml_member) + expect(result.body['member']['name']).to eq('Jane Doe') end - + it 'gets a list member.' do result = @mg_obj.get("lists/#{@ml_address}/members/#{@ml_member}") result.to_h! - expect(result.body["member"]["address"]).to eq(@ml_member) - expect(result.body["member"]["name"]).to eq('Jane Doe') + expect(result.body['member']['address']).to eq(@ml_member) + expect(result.body['member']['name']).to eq('Jane Doe') end it 'updates a list member.' do result = @mg_obj.put("lists/#{@ml_address}/members/#{@ml_member}", - {:name => 'Jane Doe Update', - :subscribed => false}) + { name: 'Jane Doe Update', + subscribed: false }) result.to_h! - expect(result.body["message"]).to eq("Mailing list member has been updated") - expect(result.body["member"]["address"]).to eq(@ml_member) - expect(result.body["member"]["name"]).to eq('Jane Doe Update') - expect(result.body["member"]["subscribed"]).to eq(false) + expect(result.body['message']).to eq('Mailing list member has been updated') + expect(result.body['member']['address']).to eq(@ml_member) + expect(result.body['member']['name']).to eq('Jane Doe Update') + expect(result.body['member']['subscribed']).to eq(false) end it 'removes a list member' do @mg_obj.delete("lists/#{@ml_address}/members/#{@ml_member}") @mg_obj.delete("lists/#{@ml_address}") end - end diff --git a/spec/integration/list_spec.rb b/spec/integration/list_spec.rb index ecc8901f..0bd81526 100644 --- a/spec/integration/list_spec.rb +++ b/spec/integration/list_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "mailing_list" } +vcr_opts = { cassette_name: 'mailing_list' } describe 'For the Mailing Lists endpoint', vcr: vcr_opts do before(:all) do @@ -11,48 +13,47 @@ end it 'creates a list' do - result = @mg_obj.post("lists", {:address => @ml_address, - :name => 'Integration Test List', - :description => 'This list should be deleted automatically.', - :access_level => 'members'}) + result = @mg_obj.post('lists', { address: @ml_address, + name: 'Integration Test List', + description: 'This list should be deleted automatically.', + access_level: 'members' }) result.to_h! - expect(result.body["message"]).to eq("Mailing list has been created") - expect(result.body["list"]["address"]).to eq(@ml_address) - expect(result.body["list"]["name"]).to eq('Integration Test List') + expect(result.body['message']).to eq('Mailing list has been created') + expect(result.body['list']['address']).to eq(@ml_address) + expect(result.body['list']['name']).to eq('Integration Test List') end it 'gets a list.' do result = @mg_obj.get("lists/#{@ml_address}") result.to_h! - expect(result.body["list"]["address"]).to eq(@ml_address) - expect(result.body["list"]["name"]).to eq('Integration Test List') + expect(result.body['list']['address']).to eq(@ml_address) + expect(result.body['list']['name']).to eq('Integration Test List') end it 'gets a list of all lists.' do - result = @mg_obj.get("lists", {:limit => 50}) + result = @mg_obj.get('lists', { limit: 50 }) result.to_h! - expect(result.body["total_count"]).to be > 0 + expect(result.body['total_count']).to be > 0 end it 'updates a list.' do result = @mg_obj.put("lists/#{@ml_address}", - {:address => @ml_address, - :name => 'Integration Test List Update', - :description => 'This list should be deleted automatically.', - :access_level => 'readonly'}) + { address: @ml_address, + name: 'Integration Test List Update', + description: 'This list should be deleted automatically.', + access_level: 'readonly' }) result.to_h! - expect(result.body["message"]).to eq("Mailing list has been updated") - expect(result.body["list"]["address"]).to eq(@ml_address) - expect(result.body["list"]["name"]).to eq('Integration Test List Update') - expect(result.body["list"]["access_level"]).to eq('readonly') + expect(result.body['message']).to eq('Mailing list has been updated') + expect(result.body['list']['address']).to eq(@ml_address) + expect(result.body['list']['name']).to eq('Integration Test List Update') + expect(result.body['list']['access_level']).to eq('readonly') end it 'deletes a list' do @mg_obj.delete("lists/#{@ml_address}") end - end diff --git a/spec/integration/logs_spec.rb b/spec/integration/logs_spec.rb index aa96ef2d..ebaed450 100644 --- a/spec/integration/logs_spec.rb +++ b/spec/integration/logs_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' @@ -37,65 +39,65 @@ it 'responds with account logs' do expect(logs.account_logs(options)).to eq( { - "start" => "Wed, 25 Jun 2025 00:00:00 -0000", - "end" => "Wed, 25 Jun 2025 23:00:00 -0000", - "items" => [ + 'start' => 'Wed, 25 Jun 2025 00:00:00 -0000', + 'end' => 'Wed, 25 Jun 2025 23:00:00 -0000', + 'items' => [ { - "id" => "123", - "event" => "accepted", - "@timestamp" => "2025-06-25T17:19:51.166Z", - "account" => { - "id" => "123" + 'id' => '123', + 'event' => 'accepted', + '@timestamp' => '2025-06-25T17:19:51.166Z', + 'account' => { + 'id' => '123' }, - "method" => "HTTP", - "originating-ip" => "123.123.12.123", - "api-key-id" => "xxx", - "domain" => { - "name" => "example.mailgun.org" + 'method' => 'HTTP', + 'originating-ip' => '123.123.12.123', + 'api-key-id' => 'xxx', + 'domain' => { + 'name' => 'example.mailgun.org' }, - "recipient" => "alex@example.com", - "recipient-domain" => "example.com", - "envelope" => { - "sender" => "example.mailgun.org", - "transport" => "smtp", - "targets" => "alex@example.com" + 'recipient' => 'alex@example.com', + 'recipient-domain' => 'example.com', + 'envelope' => { + 'sender' => 'example.mailgun.org', + 'transport' => 'smtp', + 'targets' => 'alex@example.com' }, - "storage" => { - "region" => "us-east4", - "env" => "production", - "key" => "xxx", - "url" => ["https://storage.api.mailgun.net/v3/domains/example.mailgun.org/messages/123"] + 'storage' => { + 'region' => 'us-east4', + 'env' => 'production', + 'key' => 'xxx', + 'url' => ['https://storage.api.mailgun.net/v3/domains/example.mailgun.org/messages/123'] }, - "log-level" => "info", - "user-variables" => "{}", - "message" => { - "headers" => { - "to" => "alex@example.com", - "message-id" => "123@example.mailgun.org", - "from" => "bob@sending_domain.com+4", - "subject" => "The Ruby SDK is awesome!" + 'log-level' => 'info', + 'user-variables' => '{}', + 'message' => { + 'headers' => { + 'to' => 'alex@example.com', + 'message-id' => '123@example.mailgun.org', + 'from' => 'bob@sending_domain.com+4', + 'subject' => 'The Ruby SDK is awesome!' }, - "attachments" => [ + 'attachments' => [ { - "filename" => "image.jpg", - "content-type" => "image/jpeg", - "size" => 16712 + 'filename' => 'image.jpg', + 'content-type' => 'image/jpeg', + 'size' => 16_712 } ], - "size" => 23476 + 'size' => 23_476 }, - "flags" => { - "is-authenticated" => true, - "is-system-test" => false, - "is-routed" => false, - "is-test-mode" => false, - "is-delayed-bounce" => false, - "is-callback" => false + 'flags' => { + 'is-authenticated' => true, + 'is-system-test' => false, + 'is-routed' => false, + 'is-test-mode' => false, + 'is-delayed-bounce' => false, + 'is-callback' => false } } ], - "pagination" => {}, - "aggregates" => {} + 'pagination' => {}, + 'aggregates' => {} } ) end diff --git a/spec/integration/mailer_spec.rb b/spec/integration/mailer_spec.rb index a5d07a69..539f3554 100644 --- a/spec/integration/mailer_spec.rb +++ b/spec/integration/mailer_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'json' require 'logger' @@ -21,7 +23,7 @@ def plain_message(address, from, subject, headers) end end -vcr_opts = { :cassette_name => 'message_deliver' } +vcr_opts = { cassette_name: 'message_deliver' } describe 'Message deliver', vcr: vcr_opts do let(:domain) { TESTDOMAIN || 'DOMAIN.TEST' } @@ -43,7 +45,7 @@ def plain_message(address, from, subject, headers) end end -vcr_opts = { :cassette_name => 'mailer_invalid_domain' } +vcr_opts = { cassette_name: 'mailer_invalid_domain' } describe 'Invalid domain', vcr: vcr_opts do let(:domain) { 'not-our-doma.in' } @@ -56,6 +58,8 @@ def plain_message(address, from, subject, headers) let(:mail) { IntegrationUnitTestMailer.plain_message('sally@not-our-doma.in', "bob@#{domain}", 'subject', {}) } it 'raises expected error' do - expect { Railgun::Mailer.new(config).deliver!(mail) }.to raise_error Mailgun::Unauthorized, /Invalid Domain or API key/ + expect do + Railgun::Mailer.new(config).deliver!(mail) + end.to raise_error Mailgun::Unauthorized, /Invalid Domain or API key/ end end diff --git a/spec/integration/mailgun_spec.rb b/spec/integration/mailgun_spec.rb index 661d04f7..b6d5de1f 100644 --- a/spec/integration/mailgun_spec.rb +++ b/spec/integration/mailgun_spec.rb @@ -1,105 +1,99 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' require 'mailgun/exceptions/exceptions' -describe 'Mailgun instantiation', vcr: { :cassette_name => "instance" } do +describe 'Mailgun instantiation', vcr: { cassette_name: 'instance' } do it 'instantiates an HttpClient object' do - expect {@mg_obj = Mailgun::Client.new(APIKEY, APIHOST, APIVERSION, SSL)}.not_to raise_error + expect { @mg_obj = Mailgun::Client.new(APIKEY, APIHOST, APIVERSION, SSL) }.not_to raise_error end end -describe 'Client exceptions', vcr: { :cassette_name => "exceptions" } do +describe 'Client exceptions', vcr: { cassette_name: 'exceptions' } do before(:all) do @mg_obj = Mailgun::Client.new(APIKEY, APIHOST, APIVERSION, SSL) @domain = TESTDOMAIN || 'DOMAIN.TEST' end it 'display useful error information' do - begin - @mg_obj.send_message("not-our-doma.in", { - :from => "sally@not-our-doma.in", - :to => "bob@#{@domain}", - :subject => 'Exception Integration Test', - :text => 'INTEGRATION TESTING' - }) - rescue Mailgun::CommunicationError => err - expect(err.message).to include('404') - expect(err.message).to include('Domain not found: not-our-doma.in') - else - fail - end + @mg_obj.send_message('not-our-doma.in', { + from: 'sally@not-our-doma.in', + to: "bob@#{@domain}", + subject: 'Exception Integration Test', + text: 'INTEGRATION TESTING' + }) + rescue Mailgun::CommunicationError => e + expect(e.message).to include('404') + expect(e.message).to include('Domain not found: not-our-doma.in') + else + raise end end -describe 'Client exceptions', vcr: { :cassette_name => "exceptions-invalid-api-key" } do +describe 'Client exceptions', vcr: { cassette_name: 'exceptions-invalid-api-key' } do before(:all) do @mg_obj = Mailgun::Client.new(APIKEY, APIHOST, APIVERSION, SSL) @domain = TESTDOMAIN || 'DOMAIN.TEST' end it 'displays error information that API key is invalid' do - begin - @mg_obj.send_message(@domain, { - :from => "sally@#{@domain}", - :to => "sally@#{@domain}", - :subject => 'Exception Integration Test', - :text => 'INTEGRATION TESTING' - }) - rescue Mailgun::Unauthorized => err - expect(err.message).to include('401') - expect(err.message).to include('Invalid Domain or API key') - else - fail - end + @mg_obj.send_message(@domain, { + from: "sally@#{@domain}", + to: "sally@#{@domain}", + subject: 'Exception Integration Test', + text: 'INTEGRATION TESTING' + }) + rescue Mailgun::Unauthorized => e + expect(e.message).to include('401') + expect(e.message).to include('Invalid Domain or API key') + else + raise end end -describe 'Client exceptions', vcr: { :cassette_name => "exceptions-invalid-data" } do +describe 'Client exceptions', vcr: { cassette_name: 'exceptions-invalid-data' } do before(:all) do @mg_obj = Mailgun::Client.new(APIKEY, APIHOST, APIVERSION, SSL) @domain = TESTDOMAIN || 'DOMAIN.TEST' end it 'display useful error information' do - begin - @mg_obj.send_message(@domain, { - :from => "sally@#{@domain}", - :to => "sally#{@domain}", - :subject => 'Exception Integration Test', - :text => 'INTEGRATION TESTING' - }) - rescue Mailgun::BadRequest => err - expect(err.message).to include('400') - expect(err.message).to include('to parameter is not a valid address. please check documentation') - else - fail - end + @mg_obj.send_message(@domain, { + from: "sally@#{@domain}", + to: "sally#{@domain}", + subject: 'Exception Integration Test', + text: 'INTEGRATION TESTING' + }) + rescue Mailgun::BadRequest => e + expect(e.message).to include('400') + expect(e.message).to include('to parameter is not a valid address. please check documentation') + else + raise end end -describe 'Client exceptions', vcr: { :cassette_name => "exceptions-not-allowed" } do +describe 'Client exceptions', vcr: { cassette_name: 'exceptions-not-allowed' } do before(:all) do @mg_obj = Mailgun::Client.new(APIKEY, APIHOST, APIVERSION, SSL) @domain = TESTDOMAIN || 'DOMAIN.TEST' end it 'display useful error information' do - begin - @mg_obj.send_message(@domain, { - :from => "invalid@#{@domain}", - :to => "invalid#{@domain}", - :subject => 'Exception Integration Test', - :text => 'INTEGRATION TESTING' - }) - rescue Mailgun::CommunicationError => err - expect(err.message).to include('403') - else - fail - end + @mg_obj.send_message(@domain, { + from: "invalid@#{@domain}", + to: "invalid#{@domain}", + subject: 'Exception Integration Test', + text: 'INTEGRATION TESTING' + }) + rescue Mailgun::CommunicationError => e + expect(e.message).to include('403') + else + raise end end -describe 'The method send_message()', vcr: { :cassette_name => "send_message" } do +describe 'The method send_message()', vcr: { cassette_name: 'send_message' } do before(:all) do @mg_obj = Mailgun::Client.new(APIKEY, APIHOST, APIVERSION, SSL) @domain = TESTDOMAIN || 'DOMAIN.TEST' @@ -107,15 +101,14 @@ it 'sends a standard message in test mode.' do @mg_obj.enable_test_mode! - result = @mg_obj.send_message(@domain, {:from => "bob@#{@domain}", - :to => "sally@#{@domain}", - :subject => 'Hash Integration Test', - :text => 'INTEGRATION TESTING', - 'o:testmode' => true} - ) + result = @mg_obj.send_message(@domain, { :from => "bob@#{@domain}", + :to => "sally@#{@domain}", + :subject => 'Hash Integration Test', + :text => 'INTEGRATION TESTING', + 'o:testmode' => true }) result.to_h! - expect(result.body).to include("message") - expect(result.body).to include("id") + expect(result.body).to include('message') + expect(result.body).to include('id') end it 'fakes message send while in *client* test mode' do @@ -123,10 +116,10 @@ expect(@mg_obj.test_mode?).to eq(true) - data = { :from => "joe@#{@domain}", - :to => "bob@#{@domain}", - :subject => "Test", - :text => "Test Data" } + data = { from: "joe@#{@domain}", + to: "bob@#{@domain}", + subject: 'Test', + text: 'Test Data' } uuid = 'uuid' allow(SecureRandom).to receive(:uuid).and_return(uuid) @@ -135,27 +128,27 @@ result.to_h! - expect(result.body).to include("message") - expect(result.body).to include("id") + expect(result.body).to include('message') + expect(result.body).to include('id') expect(result.code).to eq(200) expect(result.body['id']).to eq("test-mode-mail-#{uuid}@localhost") - expect(result.body['message']).to eq("Queued. Thank you.") + expect(result.body['message']).to eq('Queued. Thank you.') end it 'sends a message builder message in test mode.' do - mb_obj = Mailgun::MessageBuilder.new() - mb_obj.from("sender@#{@domain}", {'first' => 'Sending', 'last' => 'User'}) - mb_obj.add_recipient(:to, "recipient@#{@domain}", {'first' => 'Recipient', 'last' => 'User'}) - mb_obj.subject("Message Builder Integration Test") - mb_obj.body_text("This is the text body.") + mb_obj = Mailgun::MessageBuilder.new + mb_obj.from("sender@#{@domain}", { 'first' => 'Sending', 'last' => 'User' }) + mb_obj.add_recipient(:to, "recipient@#{@domain}", { 'first' => 'Recipient', 'last' => 'User' }) + mb_obj.subject('Message Builder Integration Test') + mb_obj.body_text('This is the text body.') mb_obj.test_mode(true) result = @mg_obj.send_message(@domain, mb_obj) result.to_h! - expect(result.body).to include("message") - expect(result.body).to include("id") + expect(result.body).to include('message') + expect(result.body).to include('id') end it 'sends a custom MIME message in test mode.' do @@ -175,15 +168,15 @@ Testing some Mailgun awesomness!' - message_params = {:from => "bobby@#{@domain}", - :to => "sally@#{@domain}", - :message => mime_string} + message_params = { from: "bobby@#{@domain}", + to: "sally@#{@domain}", + message: mime_string } result = @mg_obj.send_message(@domain, message_params) result.to_h! - expect(result.body).to include("message") - expect(result.body).to include("id") + expect(result.body).to include('message') + expect(result.body).to include('id') end it 'receives success response code' do @@ -191,10 +184,10 @@ expect(@mg_obj.test_mode?).to eq(true) - data = { :from => "joe@#{@domain}", - :to => "bob@#{@domain}", - :subject => "Test", - :text => "Test Data" } + data = { from: "joe@#{@domain}", + to: "bob@#{@domain}", + subject: 'Test', + text: 'Test Data' } result = @mg_obj.send_message(@domain, data) result.to_h! @@ -202,4 +195,3 @@ expect(result.success?).to be(true) end end - diff --git a/spec/integration/metrics_spec.rb b/spec/integration/metrics_spec.rb index c10bb6fd..d8ebd1bd 100644 --- a/spec/integration/metrics_spec.rb +++ b/spec/integration/metrics_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' @@ -10,11 +12,11 @@ let(:options) do { resolution: 'hour', - metrics: [ - 'accepted_count', - 'delivered_count', - 'clicked_rate', - 'opened_rate' + metrics: %w[ + accepted_count + delivered_count + clicked_rate + opened_rate ], include_aggregates: true, start: 'Tue, 26 Nov 2024 20:56:50 -0500', @@ -42,48 +44,47 @@ it 'responds with account metrics' do expect(metrics.account_metrics(options)).to eq( { - "start" => "Fri, 01 Nov 2024 01:00:00 +0000", - "end" => "Sun, 01 Dec 2024 01:00:00 +0000", - "resolution" => "hour", - "duration" => "1m", - "dimensions" => ["time"], - "pagination" => { - "sort" => "", "skip" => 0, "limit" => 1500, "total" => 3 + 'start' => 'Fri, 01 Nov 2024 01:00:00 +0000', + 'end' => 'Sun, 01 Dec 2024 01:00:00 +0000', + 'resolution' => 'hour', + 'duration' => '1m', + 'dimensions' => ['time'], + 'pagination' => { + 'sort' => '', 'skip' => 0, 'limit' => 1500, 'total' => 3 }, - "items" => [{ - "dimensions" => [{ - "dimension" => "time", - "value" => "Wed, 27 Nov 2024 12:00:00 +0000", - "display_value" => "Wed, 27 Nov 2024 12:00:00 +0000" - }], - "metrics" => { - "accepted_count" => 1, "delivered_count" => 1, "opened_rate" => "0.0000", "clicked_rate" => "0.0000" - } - }, - { - "dimensions" => [{ - "dimension" => "time", - "value" => "Wed, 27 Nov 2024 13:00:00 +0000", - "display_value" => "Wed, 27 Nov 2024 13:00:00 +0000" - }], - "metrics" => { - "accepted_count" => 1, "delivered_count" => 1, "opened_rate" => "0.0000", "clicked_rate" => "0.0000" - } - }, - { - "dimensions" => [{ - "dimension" => "time", - "value" => "Thu, 28 Nov 2024 15:00:00 +0000", - "display_value" => "Thu, 28 Nov 2024 15:00:00 +0000" - }], - "metrics" => { - "accepted_count" => 1, "delivered_count" => 1, "opened_rate" => "0.0000", "clicked_rate" => "0.0000" - } + 'items' => [{ + 'dimensions' => [{ + 'dimension' => 'time', + 'value' => 'Wed, 27 Nov 2024 12:00:00 +0000', + 'display_value' => 'Wed, 27 Nov 2024 12:00:00 +0000' + }], + 'metrics' => { + 'accepted_count' => 1, 'delivered_count' => 1, 'opened_rate' => '0.0000', 'clicked_rate' => '0.0000' } - ], - "aggregates" => { - "metrics" => { - "accepted_count" => 3, "delivered_count" => 3, "opened_rate" => "0.0000", "clicked_rate" => "0.0000" + }, + { + 'dimensions' => [{ + 'dimension' => 'time', + 'value' => 'Wed, 27 Nov 2024 13:00:00 +0000', + 'display_value' => 'Wed, 27 Nov 2024 13:00:00 +0000' + }], + 'metrics' => { + 'accepted_count' => 1, 'delivered_count' => 1, 'opened_rate' => '0.0000', 'clicked_rate' => '0.0000' + } + }, + { + 'dimensions' => [{ + 'dimension' => 'time', + 'value' => 'Thu, 28 Nov 2024 15:00:00 +0000', + 'display_value' => 'Thu, 28 Nov 2024 15:00:00 +0000' + }], + 'metrics' => { + 'accepted_count' => 1, 'delivered_count' => 1, 'opened_rate' => '0.0000', 'clicked_rate' => '0.0000' + } + }], + 'aggregates' => { + 'metrics' => { + 'accepted_count' => 3, 'delivered_count' => 3, 'opened_rate' => '0.0000', 'clicked_rate' => '0.0000' } } } @@ -95,21 +96,21 @@ let(:options) do { resolution: 'hour', - metrics: [ - 'email_preview_count', - 'email_preview_failed_count', - 'email_validation_bulk_count', - 'email_validation_count', - 'email_validation_list_count', - 'email_validation_mailgun_count', - 'email_validation_mailjet_count', - 'email_validation_public_count', - 'email_validation_single_count', - 'email_validation_valid_count', - 'link_validation_count', - 'link_validation_failed_count', - 'processed_count', - 'seed_test_count' + metrics: %w[ + email_preview_count + email_preview_failed_count + email_validation_bulk_count + email_validation_count + email_validation_list_count + email_validation_mailgun_count + email_validation_mailjet_count + email_validation_public_count + email_validation_single_count + email_validation_valid_count + link_validation_count + link_validation_failed_count + processed_count + seed_test_count ], include_aggregates: true, start: 'Tue, 26 Nov 2024 20:56:50 -0500', @@ -137,78 +138,77 @@ it 'responds with account usage metrics' do expect(metrics.account_usage_metrics(options)).to eq( { - "start" => "Tue, 29 Oct 2024 01:00:00 +0000", - "end" => "Fri, 29 Nov 2024 01:00:00 +0000", - "resolution" => "hour", - "duration" => "1m", - "dimensions" => ["time"], - "pagination" => { - "sort" => "", "skip" => 0, "limit" => 1500, "total" => 2 + 'start' => 'Tue, 29 Oct 2024 01:00:00 +0000', + 'end' => 'Fri, 29 Nov 2024 01:00:00 +0000', + 'resolution' => 'hour', + 'duration' => '1m', + 'dimensions' => ['time'], + 'pagination' => { + 'sort' => '', 'skip' => 0, 'limit' => 1500, 'total' => 2 }, - "items" => [{ - "dimensions" => [{ - "dimension" => "time", - "value" => "Wed, 27 Nov 2024 00:00:00 +0000", - "display_value" => "Wed, 27 Nov 2024 00:00:00 +0000" - }], - "metrics" => { - "processed_count" => 2, - "email_validation_count" => 0, - "email_validation_public_count" => 0, - "email_validation_valid_count" => 0, - "email_validation_single_count" => 0, - "email_validation_bulk_count" => 0, - "email_validation_list_count" => 0, - "email_validation_mailgun_count" => 0, - "email_validation_mailjet_count" => 0, - "email_preview_count" => 0, - "email_preview_failed_count" => 0, - "link_validation_count" => 0, - "link_validation_failed_count" => 0, - "seed_test_count" => 0 - } - }, - { - "dimensions" => [{ - "dimension" => "time", - "value" => "Thu, 28 Nov 2024 00:00:00 +0000", - "display_value" => "Thu, 28 Nov 2024 00:00:00 +0000" - }], - "metrics" => { - "processed_count" => 1, - "email_validation_count" => 0, - "email_validation_public_count" => 0, - "email_validation_valid_count" => 0, - "email_validation_single_count" => 0, - "email_validation_bulk_count" => 0, - "email_validation_list_count" => 0, - "email_validation_mailgun_count" => 0, - "email_validation_mailjet_count" => 0, - "email_preview_count" => 0, - "email_preview_failed_count" => 0, - "link_validation_count" => 0, - "link_validation_failed_count" => 0, - "seed_test_count" => 0 - } + 'items' => [{ + 'dimensions' => [{ + 'dimension' => 'time', + 'value' => 'Wed, 27 Nov 2024 00:00:00 +0000', + 'display_value' => 'Wed, 27 Nov 2024 00:00:00 +0000' + }], + 'metrics' => { + 'processed_count' => 2, + 'email_validation_count' => 0, + 'email_validation_public_count' => 0, + 'email_validation_valid_count' => 0, + 'email_validation_single_count' => 0, + 'email_validation_bulk_count' => 0, + 'email_validation_list_count' => 0, + 'email_validation_mailgun_count' => 0, + 'email_validation_mailjet_count' => 0, + 'email_preview_count' => 0, + 'email_preview_failed_count' => 0, + 'link_validation_count' => 0, + 'link_validation_failed_count' => 0, + 'seed_test_count' => 0 } - ], - "aggregates" => { - "metrics" => { - "permanent_failed_count" => 0, - "processed_count" => 3, - "email_validation_count" => 0, - "email_validation_public_count" => 0, - "email_validation_valid_count" => 0, - "email_validation_single_count" => 0, - "email_validation_bulk_count" => 0, - "email_validation_list_count" => 0, - "email_validation_mailgun_count" => 0, - "email_validation_mailjet_count" => 0, - "email_preview_count" => 0, - "email_preview_failed_count" => 0, - "link_validation_count" => 0, - "link_validation_failed_count" => 0, - "seed_test_count" => 0 + }, + { + 'dimensions' => [{ + 'dimension' => 'time', + 'value' => 'Thu, 28 Nov 2024 00:00:00 +0000', + 'display_value' => 'Thu, 28 Nov 2024 00:00:00 +0000' + }], + 'metrics' => { + 'processed_count' => 1, + 'email_validation_count' => 0, + 'email_validation_public_count' => 0, + 'email_validation_valid_count' => 0, + 'email_validation_single_count' => 0, + 'email_validation_bulk_count' => 0, + 'email_validation_list_count' => 0, + 'email_validation_mailgun_count' => 0, + 'email_validation_mailjet_count' => 0, + 'email_preview_count' => 0, + 'email_preview_failed_count' => 0, + 'link_validation_count' => 0, + 'link_validation_failed_count' => 0, + 'seed_test_count' => 0 + } + }], + 'aggregates' => { + 'metrics' => { + 'permanent_failed_count' => 0, + 'processed_count' => 3, + 'email_validation_count' => 0, + 'email_validation_public_count' => 0, + 'email_validation_valid_count' => 0, + 'email_validation_single_count' => 0, + 'email_validation_bulk_count' => 0, + 'email_validation_list_count' => 0, + 'email_validation_mailgun_count' => 0, + 'email_validation_mailjet_count' => 0, + 'email_preview_count' => 0, + 'email_preview_failed_count' => 0, + 'link_validation_count' => 0, + 'link_validation_failed_count' => 0, + 'seed_test_count' => 0 } } } diff --git a/spec/integration/routes_spec.rb b/spec/integration/routes_spec.rb index 00b80f42..f13c44ba 100644 --- a/spec/integration/routes_spec.rb +++ b/spec/integration/routes_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "routes", :match_requests_on => [:uri, :method, :body] } +vcr_opts = { cassette_name: 'routes', match_requests_on: %i[uri method body] } describe 'For the Routes endpoint', order: :defined, vcr: vcr_opts do before(:all) do @@ -12,79 +14,78 @@ end it 'creates a route' do - result = @mg_obj.post("routes", { priority: 10, - description: 'Integration Test Route', - expression: "match_recipient(\"#{@forward_to}\")", - action: "forward(\"#{@recipient}\")" }) + result = @mg_obj.post('routes', { priority: 10, + description: 'Integration Test Route', + expression: "match_recipient(\"#{@forward_to}\")", + action: "forward(\"#{@recipient}\")" }) result.to_h! - expect(result.body["message"]).to eq("Route has been created") - expect(result.body["route"]["description"]).to eq("Integration Test Route") - expect(result.body["route"]["actions"]).to include("forward(\"#{@recipient}\")") - expect(result.body["route"]["expression"]).to include("match_recipient(\"#{@forward_to}\")") - expect(result.body["route"]["priority"]).to eq(10) + expect(result.body['message']).to eq('Route has been created') + expect(result.body['route']['description']).to eq('Integration Test Route') + expect(result.body['route']['actions']).to include("forward(\"#{@recipient}\")") + expect(result.body['route']['expression']).to include("match_recipient(\"#{@forward_to}\")") + expect(result.body['route']['priority']).to eq(10) end it 'creates a route with multiple actions' do - result = @mg_obj.post("routes", { priority: 10, - description: 'Integration Test Route', - expression: "match_recipient(\"#{@forward_to}\")", - action: ["forward(\"#{@recipient}\")", "stop()"] }) + result = @mg_obj.post('routes', { priority: 10, + description: 'Integration Test Route', + expression: "match_recipient(\"#{@forward_to}\")", + action: ["forward(\"#{@recipient}\")", 'stop()'] }) result.to_h! - expect(result.body["message"]).to eq("Route has been created") - expect(result.body["route"]["description"]).to eq("Integration Test Route") - expect(result.body["route"]["actions"].count).to eq 2 - expect(result.body["route"]["actions"][0]).to include("forward(\"#{@recipient}\")") - expect(result.body["route"]["actions"][1]).to include("stop()") - expect(result.body["route"]["expression"]).to include("match_recipient(\"#{@forward_to}\")") - expect(result.body["route"]["priority"]).to eq(10) + expect(result.body['message']).to eq('Route has been created') + expect(result.body['route']['description']).to eq('Integration Test Route') + expect(result.body['route']['actions'].count).to eq 2 + expect(result.body['route']['actions'][0]).to include("forward(\"#{@recipient}\")") + expect(result.body['route']['actions'][1]).to include('stop()') + expect(result.body['route']['expression']).to include("match_recipient(\"#{@forward_to}\")") + expect(result.body['route']['priority']).to eq(10) end it 'gets a list of all routes.' do - result = @mg_obj.get("routes", {:limit => 50}) + result = @mg_obj.get('routes', { limit: 50 }) result.to_h! - expect(result.body["total_count"]).to be > 0 + expect(result.body['total_count']).to be > 0 end it 'gets the route.' do - result = @mg_obj.get("routes", {:limit => 1}) + result = @mg_obj.get('routes', { limit: 1 }) route_id = result.to_h['items'].first['id'] result = @mg_obj.get("routes/#{route_id}") result.to_h! - expect(result.body["route"]["description"]).to eq("Integration Test Route") - expect(result.body["route"]["actions"]).to include("forward(\"#{@recipient}\")") - expect(result.body["route"]["expression"]).to include("match_recipient(\"#{@forward_to}\")") - expect(result.body["route"]["priority"]).to eq(10) + expect(result.body['route']['description']).to eq('Integration Test Route') + expect(result.body['route']['actions']).to include("forward(\"#{@recipient}\")") + expect(result.body['route']['expression']).to include("match_recipient(\"#{@forward_to}\")") + expect(result.body['route']['priority']).to eq(10) end it 'updates the route.' do - result = @mg_obj.get("routes", {:limit => 1}) + result = @mg_obj.get('routes', { limit: 1 }) route_id = result.to_h['items'].first['id'] - result = @mg_obj.put("routes/#{route_id}", {:priority => 10, - :description => 'Integration Test Route Update', - :expression => "match_recipient(\"#{@forward_to}\")", - :action => "forward(\"#{@recipient}\")"}) + result = @mg_obj.put("routes/#{route_id}", { priority: 10, + description: 'Integration Test Route Update', + expression: "match_recipient(\"#{@forward_to}\")", + action: "forward(\"#{@recipient}\")" }) result.to_h! - expect(result.body["message"]).to eq("Route has been updated") - expect(result.body["description"]).to eq("Integration Test Route Update") - expect(result.body["actions"]).to include("forward(\"#{@recipient}\")") - expect(result.body["expression"]).to include("match_recipient(\"#{@forward_to}\")") - expect(result.body["priority"]).to eq(10) + expect(result.body['message']).to eq('Route has been updated') + expect(result.body['description']).to eq('Integration Test Route Update') + expect(result.body['actions']).to include("forward(\"#{@recipient}\")") + expect(result.body['expression']).to include("match_recipient(\"#{@forward_to}\")") + expect(result.body['priority']).to eq(10) end it 'removes a route' do - result = @mg_obj.get("routes", {:limit => 1}) + result = @mg_obj.get('routes', { limit: 1 }) route_id = result.to_h['items'].first['id'] @mg_obj.delete("routes/#{route_id}") result.to_h! end - end diff --git a/spec/integration/stats_spec.rb b/spec/integration/stats_spec.rb index 03c4453e..3555a081 100644 --- a/spec/integration/stats_spec.rb +++ b/spec/integration/stats_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "stats" } +vcr_opts = { cassette_name: 'stats' } describe 'For the Stats endpoint', vcr: vcr_opts do before(:all) do @@ -10,6 +12,6 @@ end it 'get some stats.' do - @mg_obj.get("#{@domain}/stats", {:limit => 50, :skip => 10, :event => 'sent'}) + @mg_obj.get("#{@domain}/stats", { limit: 50, skip: 10, event: 'sent' }) end end diff --git a/spec/integration/subaccounts_spec.rb b/spec/integration/subaccounts_spec.rb index 0a4df6a2..20be7199 100644 --- a/spec/integration/subaccounts_spec.rb +++ b/spec/integration/subaccounts_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "subaccounts" } +vcr_opts = { cassette_name: 'subaccounts' } describe 'For the subaccounts endpoints', vcr: vcr_opts do let(:name) { 'test.subaccount' } @@ -16,7 +18,8 @@ it 'returns a list of templates' do result = @mg_obj.list - expect(result).to eq({"subaccounts"=>[{"id"=>"xxx", "name"=>"test-ruby-lib", "status"=>"open"}], "total"=>1}) + expect(result).to eq({ 'subaccounts' => [{ 'id' => 'xxx', 'name' => 'test-ruby-lib', 'status' => 'open' }], + 'total' => 1 }) end end @@ -24,26 +27,23 @@ it 'creates the subaccount' do result = @mg_obj.create(name) - expect(result).to eq({"subaccount"=>{"id"=>"xxx", "name"=>"test.subaccount", "status"=>"open"}}) + expect(result).to eq({ 'subaccount' => { 'id' => 'xxx', 'name' => 'test.subaccount', 'status' => 'open' } }) end end - describe '#info' do it 'gets the templates info' do result = @mg_obj.info(subaccount_id) - expect(result).to eq({"subaccount"=>{"id"=>"xxx", "name"=>"test-ruby-lib", "status"=>"open"}}) + expect(result).to eq({ 'subaccount' => { 'id' => 'xxx', 'name' => 'test-ruby-lib', 'status' => 'open' } }) end end - - describe '#enable' do it 'enables the subaccount' do result = @mg_obj.enable(subaccount_id) - expect(result).to eq({"subaccount"=>{"id"=>"xxx", "name"=>"test-ruby-lib", "status"=>"open"}}) + expect(result).to eq({ 'subaccount' => { 'id' => 'xxx', 'name' => 'test-ruby-lib', 'status' => 'open' } }) end end @@ -51,8 +51,7 @@ it 'disables the subaccount' do result = @mg_obj.disable(subaccount_id) - expect(result).to eq({"subaccount"=>{"id"=>"xxx", "name"=>"test-ruby-lib", "status"=>"disabled"}}) + expect(result).to eq({ 'subaccount' => { 'id' => 'xxx', 'name' => 'test-ruby-lib', 'status' => 'disabled' } }) end end - end diff --git a/spec/integration/suppressions_spec.rb b/spec/integration/suppressions_spec.rb index a49beaa3..3f0805f6 100644 --- a/spec/integration/suppressions_spec.rb +++ b/spec/integration/suppressions_spec.rb @@ -1,12 +1,13 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' require 'mailgun/suppressions' -vcr_opts = { :cassette_name => 'suppressions' } +vcr_opts = { cassette_name: 'suppressions' } describe 'For the suppressions handling class', order: :defined, vcr: vcr_opts do - before(:all) do @mg_obj = Mailgun::Client.new(APIKEY) @suppress = Mailgun::Suppressions.new(@mg_obj, TESTDOMAIN) @@ -18,10 +19,10 @@ bounces = [] @addresses.each do |addr| bounces.push({ - :address => addr, - :code => 500, - :error => 'integration testing', - }) + address: addr, + code: 500, + error: 'integration testing' + }) end response, nested = @suppress.create_bounces bounces @@ -35,9 +36,9 @@ it 'raises ParameterError if no bounce[:address] is present' do bounces = [] bounces.push({ - :code => 500, - :error => 'integration testing', - }) + code: 500, + error: 'integration testing' + }) expect { @suppress.create_bounces bounces }.to raise_error(Mailgun::ParameterError) end @@ -56,9 +57,9 @@ unsubscribes = [] @addresses.each do |addr| unsubscribes.push({ - :address => addr, - :tag => 'integration', - }) + address: addr, + tag: 'integration' + }) end response, nested = @suppress.create_unsubscribes unsubscribes @@ -73,9 +74,9 @@ unsubscribes = [] @addresses.each do |addr| unsubscribes.push({ - :address => addr, - :tags => ['integration'], - }) + address: addr, + tags: ['integration'] + }) end response, nested = @suppress.create_unsubscribes unsubscribes @@ -89,8 +90,8 @@ it 'raises ParameterError if no unsubscribe[:address] is present' do unsubscribes = [] unsubscribes.push({ - :tag => 'integration', - }) + tag: 'integration' + }) expect { @suppress.create_unsubscribes unsubscribes }.to raise_error(Mailgun::ParameterError) end @@ -108,7 +109,7 @@ it 'can batch-add complaints' do complaints = [] @addresses.each do |addr| - complaints.push :address => addr + complaints.push address: addr end response, nested = @suppress.create_complaints complaints @@ -122,8 +123,8 @@ it 'raises ParameterError if no complaint[:address] is present' do complaints = [] complaints.push({ - :tag => 'integration', - }) + tag: 'integration' + }) expect { @suppress.create_complaints complaints }.to raise_error(Mailgun::ParameterError) end diff --git a/spec/integration/templates_spec.rb b/spec/integration/templates_spec.rb index 4d9f4e1a..a8420d24 100644 --- a/spec/integration/templates_spec.rb +++ b/spec/integration/templates_spec.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "templates" } +vcr_opts = { cassette_name: 'templates' } describe 'For the templates endpoints', vcr: vcr_opts do let(:template_name) { 'test.template' } - let(:domain) { "integration-test.domain.invalid" } + let(:domain) { 'integration-test.domain.invalid' } let(:tag) { 'v2' } before(:all) do @@ -21,14 +23,14 @@ name: template_name, description: 'Test', template: '{{fname}} {{lname}}', - comment: 'test comment', - headers: '{"Subject": "{{subject}}"}', - tag: 'V1' + comment: 'test comment', + headers: '{"Subject": "{{subject}}"}', + tag: 'V1' } ) - expect(result['template']["name"]).to eq('test.template') - expect(result['template']["description"]).to eq("Test") + expect(result['template']['name']).to eq('test.template') + expect(result['template']['description']).to eq('Test') end end @@ -36,8 +38,8 @@ it 'gets the templates info' do result = @mg_obj.info(domain, 'test.template') - expect(result).to include("template") - expect(result["template"]["name"]).to eq(template_name) + expect(result).to include('template') + expect(result['template']['name']).to eq(template_name) end end @@ -88,7 +90,7 @@ } ) - expect(result['template']["version"]['tag']).to eq(tag) + expect(result['template']['version']['tag']).to eq(tag) end end @@ -96,7 +98,7 @@ it "gets the template's version info" do result = @mg_obj.info_version(domain, template_name, tag) - expect(result["template"]["version"]['tag']).to eq(tag) + expect(result['template']['version']['tag']).to eq(tag) end end @@ -121,7 +123,7 @@ it "returns template's versions" do result = @mg_obj.template_versions_list(domain, template_name) - expect(result["template"]["versions"].first).to include('tag') + expect(result['template']['versions'].first).to include('tag') end end diff --git a/spec/integration/unsubscribes_spec.rb b/spec/integration/unsubscribes_spec.rb index 2a699594..575fb849 100644 --- a/spec/integration/unsubscribes_spec.rb +++ b/spec/integration/unsubscribes_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "unsubscribes" } +vcr_opts = { cassette_name: 'unsubscribes' } describe 'For the Unsubscribes endpoint', order: :defined, vcr: vcr_opts do before(:all) do @@ -14,22 +16,22 @@ result = @mg_obj.post "#{@domain}/unsubscribes", address: @email, tag: '*' result.to_h! - expect(result.body["message"]).to eq("Address has been added to the unsubscribes table") - expect(result.body["address"]).to eq(@email) + expect(result.body['message']).to eq('Address has been added to the unsubscribes table') + expect(result.body['address']).to eq(@email) end it 'get an unsubscribee.' do result = @mg_obj.get "#{@domain}/unsubscribes/#{@email}" result.to_h! - expect(result.body["address"]).to eq(@email) + expect(result.body['address']).to eq(@email) end it 'gets a list of unsubscribes.' do result = @mg_obj.get "#{@domain}/unsubscribes" result.to_h! - expect(result.body["items"].length).to be > 0 + expect(result.body['items'].length).to be > 0 end it 'removes an unsubscribee' do @@ -37,6 +39,6 @@ result.to_h! expect(result.body['address']).to eq(@email) - expect(result.body["message"]).to eq("Unsubscribe event has been removed") + expect(result.body['message']).to eq('Unsubscribe event has been removed') end end diff --git a/spec/integration/webhook_spec.rb b/spec/integration/webhook_spec.rb index f2aad6f4..4917351f 100644 --- a/spec/integration/webhook_spec.rb +++ b/spec/integration/webhook_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' -vcr_opts = { :cassette_name => "webhooks" } +vcr_opts = { cassette_name: 'webhooks' } describe 'For the webhooks endpoint', order: :defined, vcr: vcr_opts do before(:all) do @@ -13,42 +15,41 @@ it 'creates a webhook' do result = @mg_obj.post("domains/#{@domain}/webhooks", { id: @testhook, - url: "http://example.com/mailgun/events/#{@testhook}" } ) + url: "http://example.com/mailgun/events/#{@testhook}" }) result.to_h! - expect(result.body["message"]).to eq("Webhook has been created") - expect(result.body["webhook"]["urls"]).to include("http://example.com/mailgun/events/#{@testhook}") + expect(result.body['message']).to eq('Webhook has been created') + expect(result.body['webhook']['urls']).to include("http://example.com/mailgun/events/#{@testhook}") end it 'gets a webhook.' do result = @mg_obj.get("domains/#{@domain}/webhooks/#{@testhook}") result.to_h! - expect(result.body["webhook"]["urls"]).to include("http://example.com/mailgun/events/#{@testhook}") + expect(result.body['webhook']['urls']).to include("http://example.com/mailgun/events/#{@testhook}") end it 'gets a list of all webhooks.' do result = @mg_obj.get("domains/#{@domain}/webhooks") result.to_h! - expect(result.body["webhooks"]["accepted"]["urls"]).to include("http://example.com/mailgun/events/#{@testhook}") + expect(result.body['webhooks']['accepted']['urls']).to include("http://example.com/mailgun/events/#{@testhook}") end it 'updates a webhook.' do - result = @mg_obj.put("domains/#{@domain}/webhooks/#{@testhook}", {:id => @testhook, - :url => "http://example.com/mailgun/events/#{@testhookup}"}) + result = @mg_obj.put("domains/#{@domain}/webhooks/#{@testhook}", { id: @testhook, + url: "http://example.com/mailgun/events/#{@testhookup}" }) result.to_h! - expect(result.body["message"]).to eq("Webhook has been updated") - expect(result.body["webhook"]["urls"]).to include("http://example.com/mailgun/events/#{@testhookup}") + expect(result.body['message']).to eq('Webhook has been updated') + expect(result.body['webhook']['urls']).to include("http://example.com/mailgun/events/#{@testhookup}") end it 'removes a webhook' do result = @mg_obj.delete("domains/#{@domain}/webhooks/#{@testhook}") result.to_h! - expect(result.body['message']).to eq("Webhook has been deleted") + expect(result.body['message']).to eq('Webhook has been deleted') expect(result.body['webhook']['urls']).to include("http://example.com/mailgun/events/#{@testhookup}") end - end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 8b8e9a35..89cdfa35 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'simplecov' SimpleCov.start do - add_filter "/spec/" + add_filter '/spec/' end require 'mailgun' @@ -10,22 +12,20 @@ require 'webmock/rspec' require 'rspec/its' -#WebMock.disable_net_connect!(allow_localhost: true) +# WebMock.disable_net_connect!(allow_localhost: true) require_relative 'unit/connection/test_client' -RSpec.configure do |c| - c.raise_errors_for_deprecations! -end +RSpec.configure(&:raise_errors_for_deprecations!) -APIHOST = "api.mailgun.net" -APIVERSION = "v3" +APIHOST = 'api.mailgun.net' +APIVERSION = 'v3' SSL = true # For integration tests modify .ruby-env.yml # use .ruby-env.yml.example for an example # alternatively # set environment variables as named in .ruby-env.yml.example -envfile = File.join(File.dirname(__FILE__), '..','.ruby-env.yml') +envfile = File.join(File.dirname(__FILE__), '..', '.ruby-env.yml') envs = File.exist?(envfile) ? YAML.load_file(envfile) : ENV APIKEY = envs['MAILGUN_APIKEY'] PUB_APIKEY = envs['MAILGUN_PUB_APIKEY'] diff --git a/spec/unit/connection/test_client.rb b/spec/unit/connection/test_client.rb index c6631640..cf17213b 100644 --- a/spec/unit/connection/test_client.rb +++ b/spec/unit/connection/test_client.rb @@ -1,9 +1,10 @@ +# frozen_string_literal: true + require 'time' require 'json' module Mailgun class UnitClient < Mailgun::Client - attr_reader :options, :block, :body, :code, :response def initialize(endpoint, &block) @@ -14,9 +15,10 @@ def initialize(endpoint, &block) end def [](endpoint, &new_block) - case - when block_given? then self.class.new(endpoint, &new_block) - when block then self.class.new(endpoint, &block) + if block_given? + self.class.new(endpoint, &new_block) + elsif block + self.class.new(endpoint, &block) else self.class.new(endpoint) end @@ -26,10 +28,8 @@ def send_message(working_domain, data) perform_data_validation(working_domain, data) case data when Hash - if data.has_key?(:message) - if data[:message].is_a?(String) - data[:message] = convert_string_to_file(data[:message]) - end + if data.key?(:message) + data[:message] = convert_string_to_file(data[:message]) if data[:message].is_a?(String) post("#{working_domain}/messages.mime", data) else post("#{working_domain}/messages", data) @@ -37,80 +37,86 @@ def send_message(working_domain, data) when MessageBuilder post("#{working_domain}/messages", data.message) else - raise ParameterError.new("Unknown data type for data parameter.", data) + raise ParameterError.new('Unknown data type for data parameter.', data) end end - def post(path, data) - begin - Mailgun::Response.new(response_generator(@endpoint)) - rescue => e - p e - raise CommunicationError.new(e), e.response if e.respond_to? :response - raise CommunicationError.new(e.message) - end + def post(_path, _data) + Mailgun::Response.new(response_generator(@endpoint)) + rescue StandardError => e + p e + raise CommunicationError.new(e), e.response if e.respond_to? :response + + raise CommunicationError, e.message end - def get(path, query_string = nil) - begin - Mailgun::Response.new(response_generator(@endpoint)) - rescue => e - raise CommunicationError.new(e), e.response - end + def get(_path, _query_string = nil) + Mailgun::Response.new(response_generator(@endpoint)) + rescue StandardError => e + raise CommunicationError.new(e), e.response end - def put(path, data) - begin - Mailgun::Response.new(response_generator(@endpoint)) - rescue => e - raise CommunicationError.new(e), e.response - end + def put(_path, _data) + Mailgun::Response.new(response_generator(@endpoint)) + rescue StandardError => e + raise CommunicationError.new(e), e.response end - def delete(path) - begin - Mailgun::Response.new(response_generator(@endpoint)) - rescue => e - raise CommunicationError.new(e), e.response - end + def delete(_path) + Mailgun::Response.new(response_generator(@endpoint)) + rescue StandardError => e + raise CommunicationError.new(e), e.response end private def perform_data_validation(working_domain, data) - fail ParameterError.new('Missing working domain', working_domain) unless working_domain + raise ParameterError.new('Missing working domain', working_domain) unless working_domain return true unless data.is_a?(Hash) && data.present? + message = data.respond_to?(:message) ? data.message : data - fail ParameterError.new( - 'Missing `to` recipient, message should contain at least 1 recipient', - working_domain - ) if message.fetch('to', []).empty? && message.fetch(:to, []).empty? - fail ParameterError.new( + if message.fetch('to', []).empty? && message.fetch(:to, []).empty? + raise ParameterError.new( + 'Missing `to` recipient, message should contain at least 1 recipient', + working_domain + ) + end + return unless message.fetch('from', []).empty? && message.fetch(:from, []).empty? + + raise ParameterError.new( 'Missing a `from` sender, message should contain at least 1 `from` sender', working_domain - ) if message.fetch('from', []).empty? && message.fetch(:from, []).empty? + ) end def response_generator(resource_endpoint) - if resource_endpoint == "messages" + if resource_endpoint == 'messages' t = Time.now - id = "<#{t.to_i}.#{rand(99999999)}.5817@example.com>" - return Response.from_hash({ body: JSON.generate({"message" => "Queued. Thank you.", "id" => id}) }) + id = "<#{t.to_i}.#{rand(99_999_999)}.5817@example.com>" + return Response.from_hash({ body: JSON.generate({ 'message' => 'Queued. Thank you.', 'id' => id }) }) end - if resource_endpoint == "bounces" - return Response.from_hash({ body: JSON.generate({"total_count" => 1, "items" => {"created_at" => "Fri, 21 Oct 2011 11:02:55 GMT", "status" => 550, "address" => "baz@example.com", "error" => "Message was not accepted -- invalid mailbox. Local mailbox baz@example.com is unavailable: user not found"}}) }) + if resource_endpoint == 'bounces' + return Response.from_hash({ body: JSON.generate({ 'total_count' => 1, + 'items' => { 'created_at' => 'Fri, 21 Oct 2011 11:02:55 GMT', 'status' => 550, 'address' => 'baz@example.com', + 'error' => 'Message was not accepted -- invalid mailbox. Local mailbox baz@example.com is unavailable: user not found' } }) }) end - if resource_endpoint == "lists" - return Response.from_hash({ body: JSON.generate({"member" => {"vars" => {"age" => 26}, "name" => "Foo Bar", "subscribed" => false, "address" => "bar@example.com"}, "message" => "Mailing list member has been updated"}) }) + if resource_endpoint == 'lists' + return Response.from_hash({ body: JSON.generate({ + 'member' => { 'vars' => { 'age' => 26 }, 'name' => 'Foo Bar', 'subscribed' => false, + 'address' => 'bar@example.com' }, 'message' => 'Mailing list member has been updated' + }) }) end - if resource_endpoint == "campaigns" - return Response.from_hash({ body: JSON.generate({"message" => "Campaign has been deleted", "id" => "ABC123"}) }) - end - if resource_endpoint == "events" - return Response.from_hash({ body: JSON.generate({"items" => [], "paging" => {"next"=> "https://api.mailgun.net/v3/thisisatestdomainformailgun.com/events/W3siYiI6ICIyMDE0LTA1LTA3VDAwOjQ1OjUxLjc0MDg5MiswMDowMCIsICJlIjogIjIwMTQtMDUtMDVUMDA6NDU6NTEuNzQwOTgzKzAwOjAwIn0sIHsiYiI6ICIyMDE0LTA1LTA3VDAwOjQ1OjUxLjc0MDg5MiswMDowMCIsICJlIjogIjIwMTQtMDUtMDVUMDA6NDU6NTEuNzQwOTgzKzAwOjAwIn0sIFsiZiJdLCBudWxsLCB7ImFjY291bnQuaWQiOiAiNGU4MjMwZjYxNDc2ZDg2NzEzMDBjNDc2IiwgImRvbWFpbi5uYW1lIjogInRoaXNpc2F0ZXN0ZG9tYWluZm9ybWFpbGd1bi5jb20iLCAic2V2ZXJpdHkiOiAiTk9UIGludGVybmFsIn0sIDEwMCwgbnVsbF0=", "previous"=> "https://api.mailgun.net/v2/thisisatestdomainformailgun.com/events/W3siYiI6ICIyMDE0LTA1LTA3VDAwOjQ1OjUxLjc0MDg5MiswMDowMCIsICJlIjogIjIwMTQtMDUtMDVUMDA6NDU6NTEuNzQwOTgzKzAwOjAwIn0sIHsiYiI6ICIyMDE0LTA1LTA3VDAwOjQ1OjUxLjc0MDg5MiswMDowMCIsICJlIjogIjIwMTQtMDUtMDdUMDA6NDU6NTEuNzQxODkyKzAwOjAwIn0sIFsicCIsICJmIl0sIG51bGwsIHsiYWNjb3VudC5pZCI6ICI0ZTgyMzBmNjE0NzZkODY3MTMwMGM0NzYiLCAiZG9tYWluLm5hbWUiOiAidGhpc2lzYXRlc3Rkb21haW5mb3JtYWlsZ3VuLmNvbSIsICJzZXZlcml0eSI6ICJOT1QgaW50ZXJuYWwifSwgMTAwLCBudWxsXQ=="}}) }) + if resource_endpoint == 'campaigns' + return Response.from_hash({ body: JSON.generate({ 'message' => 'Campaign has been deleted', + 'id' => 'ABC123' }) }) end + return unless resource_endpoint == 'events' + + Response.from_hash({ body: JSON.generate({ 'items' => [], + 'paging' => { + 'next' => 'https://api.mailgun.net/v3/thisisatestdomainformailgun.com/events/W3siYiI6ICIyMDE0LTA1LTA3VDAwOjQ1OjUxLjc0MDg5MiswMDowMCIsICJlIjogIjIwMTQtMDUtMDVUMDA6NDU6NTEuNzQwOTgzKzAwOjAwIn0sIHsiYiI6ICIyMDE0LTA1LTA3VDAwOjQ1OjUxLjc0MDg5MiswMDowMCIsICJlIjogIjIwMTQtMDUtMDVUMDA6NDU6NTEuNzQwOTgzKzAwOjAwIn0sIFsiZiJdLCBudWxsLCB7ImFjY291bnQuaWQiOiAiNGU4MjMwZjYxNDc2ZDg2NzEzMDBjNDc2IiwgImRvbWFpbi5uYW1lIjogInRoaXNpc2F0ZXN0ZG9tYWluZm9ybWFpbGd1bi5jb20iLCAic2V2ZXJpdHkiOiAiTk9UIGludGVybmFsIn0sIDEwMCwgbnVsbF0=', 'previous' => 'https://api.mailgun.net/v2/thisisatestdomainformailgun.com/events/W3siYiI6ICIyMDE0LTA1LTA3VDAwOjQ1OjUxLjc0MDg5MiswMDowMCIsICJlIjogIjIwMTQtMDUtMDVUMDA6NDU6NTEuNzQwOTgzKzAwOjAwIn0sIHsiYiI6ICIyMDE0LTA1LTA3VDAwOjQ1OjUxLjc0MDg5MiswMDowMCIsICJlIjogIjIwMTQtMDUtMDdUMDA6NDU6NTEuNzQxODkyKzAwOjAwIn0sIFsicCIsICJmIl0sIG51bGwsIHsiYWNjb3VudC5pZCI6ICI0ZTgyMzBmNjE0NzZkODY3MTMwMGM0NzYiLCAiZG9tYWluLm5hbWUiOiAidGhpc2lzYXRlc3Rkb21haW5mb3JtYWlsZ3VuLmNvbSIsICJzZXZlcml0eSI6ICJOT1QgaW50ZXJuYWwifSwgMTAwLCBudWxsXQ==' + } }) }) end end - end diff --git a/spec/unit/events/events_spec.rb b/spec/unit/events/events_spec.rb index c614fce3..afbcc786 100644 --- a/spec/unit/events/events_spec.rb +++ b/spec/unit/events/events_spec.rb @@ -1,31 +1,34 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'The method get' do it 'should return a proper hash of log data.' do @mg_obj = Mailgun::UnitClient.new('events') - events = Mailgun::Events.new(@mg_obj, "samples.mailgun.org") - result = events.get() + events = Mailgun::Events.new(@mg_obj, 'samples.mailgun.org') + result = events.get - expect(result.body).to include("items") - expect(result.body).to include("paging") + expect(result.body).to include('items') + expect(result.body).to include('paging') end end describe 'Pagination' do it 'should return a proper hash of log data.' do @mg_obj = Mailgun::UnitClient.new('events') - events = Mailgun::Events.new(@mg_obj, "samples.mailgun.org") - result = events.get() + events = Mailgun::Events.new(@mg_obj, 'samples.mailgun.org') + result = events.get json = JSON.parse(result.body) - expect(json).to include("paging") - expect(json["paging"]).to include("next") - expect(json["paging"]).to include("previous") + expect(json).to include('paging') + expect(json['paging']).to include('next') + expect(json['paging']).to include('previous') end it 'should calculate proper next-page url' do - events = Mailgun::Events.new(@mg_obj, "samples.mailgun.org") - output = events.send(:extract_endpoint_from, '/v3/samples.mailgun.org/events/W3siYiI6ICIyMDE3LTA1LTEwVDIwOjA2OjU0LjU3NiswMDowMCIsICJlIjogIjIwMTctMDUtMDhUMjA6MDY6NTQuNTc3KzAwOjAwIn0sIHsiYiI6ICIyMDE3LTA1LTEwVDIwOjA2OjU0LjU3NiswMDowMCIsICJlIjogIjIwMTctMDUtMDhUMjA6MDY6NTQuNTc3KzAwOjAwIn0sIFsiZiJdLCBudWxsLCBbWyJhY2NvdW50LmlkIiwgIjU4MDUyMTg2NzhmYTE2MTNjNzkwYjUwZiJdLCBbImRvbWFpbi5uYW1lIiwgInNhbmRib3gyOTcwMTUyYWYzZDM0NTU5YmZjN2U3MTcwM2E2Y2YyNC5tYWlsZ3VuLm9yZyJdXSwgMTAwLCBudWxsXQ==') + events = Mailgun::Events.new(@mg_obj, 'samples.mailgun.org') + output = events.send(:extract_endpoint_from, + '/v3/samples.mailgun.org/events/W3siYiI6ICIyMDE3LTA1LTEwVDIwOjA2OjU0LjU3NiswMDowMCIsICJlIjogIjIwMTctMDUtMDhUMjA6MDY6NTQuNTc3KzAwOjAwIn0sIHsiYiI6ICIyMDE3LTA1LTEwVDIwOjA2OjU0LjU3NiswMDowMCIsICJlIjogIjIwMTctMDUtMDhUMjA6MDY6NTQuNTc3KzAwOjAwIn0sIFsiZiJdLCBudWxsLCBbWyJhY2NvdW50LmlkIiwgIjU4MDUyMTg2NzhmYTE2MTNjNzkwYjUwZiJdLCBbImRvbWFpbi5uYW1lIiwgInNhbmRib3gyOTcwMTUyYWYzZDM0NTU5YmZjN2U3MTcwM2E2Y2YyNC5tYWlsZ3VuLm9yZyJdXSwgMTAwLCBudWxsXQ==') expect(output).to eq 'W3siYiI6ICIyMDE3LTA1LTEwVDIwOjA2OjU0LjU3NiswMDowMCIsICJlIjogIjIwMTctMDUtMDhUMjA6MDY6NTQuNTc3KzAwOjAwIn0sIHsiYiI6ICIyMDE3LTA1LTEwVDIwOjA2OjU0LjU3NiswMDowMCIsICJlIjogIjIwMTctMDUtMDhUMjA6MDY6NTQuNTc3KzAwOjAwIn0sIFsiZiJdLCBudWxsLCBbWyJhY2NvdW50LmlkIiwgIjU4MDUyMTg2NzhmYTE2MTNjNzkwYjUwZiJdLCBbImRvbWFpbi5uYW1lIiwgInNhbmRib3gyOTcwMTUyYWYzZDM0NTU5YmZjN2U3MTcwM2E2Y2YyNC5tYWlsZ3VuLm9yZyJdXSwgMTAwLCBudWxsXQ==' end @@ -34,33 +37,33 @@ describe 'The method next' do it 'should return the next series of data.' do @mg_obj = Mailgun::UnitClient.new('events') - events = Mailgun::Events.new(@mg_obj, "samples.mailgun.org") - result = events.next() + events = Mailgun::Events.new(@mg_obj, 'samples.mailgun.org') + result = events.next - expect(result.body).to include("items") - expect(result.body).to include("paging") + expect(result.body).to include('items') + expect(result.body).to include('paging') end end describe 'The method previous' do it 'should return the previous series of data.' do @mg_obj = Mailgun::UnitClient.new('events') - events = Mailgun::Events.new(@mg_obj, "samples.mailgun.org") - result = events.previous() + events = Mailgun::Events.new(@mg_obj, 'samples.mailgun.org') + result = events.previous - expect(result.body).to include("items") - expect(result.body).to include("paging") + expect(result.body).to include('items') + expect(result.body).to include('paging') end end describe 'The method each' do it 'should iterate over all event items.' do @mg_obj = Mailgun::UnitClient.new('events') - events = Mailgun::Events.new(@mg_obj, "samples.mailgun.org") + events = Mailgun::Events.new(@mg_obj, 'samples.mailgun.org') # Events from the UnitClient are actually empty. count = 0 - events.each do |e| - count = count + 1 + events.each do |_e| + count += 1 end # Better than nothing.. diff --git a/spec/unit/exceptions/exceptions_spec.rb b/spec/unit/exceptions/exceptions_spec.rb index 0aeb0d0d..00faa850 100644 --- a/spec/unit/exceptions/exceptions_spec.rb +++ b/spec/unit/exceptions/exceptions_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' RSpec.describe Mailgun::CommunicationError do @@ -9,22 +11,21 @@ end.not_to raise_error end - context "when the Response body has an `Error` property" do - it "uses the `Error` property as the API message" do + context 'when the Response body has an `Error` property' do + it 'uses the `Error` property as the API message' do subject = described_class.new('Boom!', { status: 401, body: '{"Error":"unauthorized"}' }) - expect(subject.message).to eq("Boom!: unauthorized") + expect(subject.message).to eq('Boom!: unauthorized') end end - context "when the Response body has an `error` property" do - it "uses the `Error` property as the API message" do + context 'when the Response body has an `error` property' do + it 'uses the `Error` property as the API message' do subject = described_class.new('Boom!', { status: 401, body: '{"error":"not found"}' }) - expect(subject.message).to eq("Boom!: not found") + expect(subject.message).to eq('Boom!: not found') end end - end end end diff --git a/spec/unit/lists/opt_in_handler_spec.rb b/spec/unit/lists/opt_in_handler_spec.rb index b82012f2..de246249 100644 --- a/spec/unit/lists/opt_in_handler_spec.rb +++ b/spec/unit/lists/opt_in_handler_spec.rb @@ -1,22 +1,24 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'The method generate_hash' do before(:each) do - @mailing_list = "mylist@example.com" - @secret_app_id = "mysupersecretpassword" - @recipient_address = "bob@example.com" - @precalculated_hash = "eyJoIjoiMmY3ZmY1MzFlOGJmMjA0OWNhMTI3ZmU4ZTQyNjZkOTljYzhkMTdk%0AMiIsInAiOiJleUpzSWpvaWJYbHNhWE4wUUdWNFlXMXdiR1V1WTI5dElpd2lj%0AaUk2SW1KdllrQmxlR0Z0Y0d4bExtTnZcbmJTSjlcbiJ9%0A" + @mailing_list = 'mylist@example.com' + @secret_app_id = 'mysupersecretpassword' + @recipient_address = 'bob@example.com' + @precalculated_hash = 'eyJoIjoiMmY3ZmY1MzFlOGJmMjA0OWNhMTI3ZmU4ZTQyNjZkOTljYzhkMTdk%0AMiIsInAiOiJleUpzSWpvaWJYbHNhWE4wUUdWNFlXMXdiR1V1WTI5dElpd2lj%0AaUk2SW1KdllrQmxlR0Z0Y0d4bExtTnZcbmJTSjlcbiJ9%0A' end it 'generates a web safe hash for the recipient wishing to subscribe' do my_hash = Mailgun::OptInHandler.generate_hash(@mailing_list, @secret_app_id, @recipient_address) - + expect(my_hash).to eq(@precalculated_hash) end it 'generates a web safe hash for the recipient wishing to subscribe' do validate_result = Mailgun::OptInHandler.validate_hash(@secret_app_id, @precalculated_hash) - + expect(validate_result.length).to eq(2) expect(validate_result['recipient_address']).to eq(@recipient_address) expect(validate_result['mailing_list']).to eq(@mailing_list) diff --git a/spec/unit/mailgun_spec.rb b/spec/unit/mailgun_spec.rb index 0d189f4b..0d1c6c68 100644 --- a/spec/unit/mailgun_spec.rb +++ b/spec/unit/mailgun_spec.rb @@ -1,26 +1,28 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'Mailgun instantiation' do it 'instantiates an HttpClient object' do - expect {@mg_obj = Mailgun::UnitClient.new("messages")}.not_to raise_error + expect { @mg_obj = Mailgun::UnitClient.new('messages') }.not_to raise_error end end describe 'The method send_message()' do before(:each) do - @mg_obj = Mailgun::UnitClient.new("messages") - @domain = "test.com" - @list_address = "mylist@test.com" - @member_address = "subscribee@test.com" + @mg_obj = Mailgun::UnitClient.new('messages') + @domain = 'test.com' + @list_address = 'mylist@test.com' + @member_address = 'subscribee@test.com' end it 'accepts only specific data types' do - @mb_obj = Mailgun::MessageBuilder.new() + @mb_obj = Mailgun::MessageBuilder.new @mh_obj = {} - expect {@mg_obj.send_message("test.com", "incorrect data")}.to raise_error Mailgun::ParameterError - expect {@mg_obj.send_message("test.com", @mb_obj)}.not_to raise_error - expect {@mg_obj.send_message("test.com", @mh_obj)}.not_to raise_error + expect { @mg_obj.send_message('test.com', 'incorrect data') }.to raise_error Mailgun::ParameterError + expect { @mg_obj.send_message('test.com', @mb_obj) }.not_to raise_error + expect { @mg_obj.send_message('test.com', @mh_obj) }.not_to raise_error end it 'sends a message' do @@ -28,12 +30,12 @@ 'to' => 'bob@example.com', 'subject' => 'Test', 'text' => 'Test Data' } - result = @mg_obj.send_message("testdomain.com", data) + result = @mg_obj.send_message('testdomain.com', data) result.to_h! - expect(result.body).to include("message") - expect(result.body).to include("id") + expect(result.body).to include('message') + expect(result.body).to include('id') end it 'opens the message MIME and sends the MIME message.' do @@ -42,119 +44,118 @@ 'message' => 'Sample Data/mime.txt', 'from' => 'joe@test.com' } - result = @mg_obj.send_message("testdomain.com", data) + result = @mg_obj.send_message('testdomain.com', data) result.to_h! - expect(result.body).to include("message") - expect(result.body).to include("id") + expect(result.body).to include('message') + expect(result.body).to include('id') end context 'when domain is missing' do it 'shows failure message' do - expect(@mg_obj).to receive(:fail) + expect(@mg_obj).to receive(:raise) @mg_obj.send_message(nil, {}) end end context 'when to is missing' do it 'shows failure message' do - data = { - 'to' => '', - 'message' => 'Sample Data/mime.txt', - 'from' => 'joe@test.com' - } - expect(@mg_obj).to receive(:fail) - @mg_obj.send_message("testdomain.com", data) + data = { + 'to' => '', + 'message' => 'Sample Data/mime.txt', + 'from' => 'joe@test.com' + } + expect(@mg_obj).to receive(:raise) + @mg_obj.send_message('testdomain.com', data) end end end describe 'The method post()' do before(:each) do - @mg_obj = Mailgun::UnitClient.new("messages") - @domain = "test.com" + @mg_obj = Mailgun::UnitClient.new('messages') + @domain = 'test.com' end it 'in this case, sends a simple message.' do - data = {'from' => 'joe@test.com', - 'to' => 'bob@example.com', - 'subject' => 'Test', - 'text' => 'Test Data'} + data = { 'from' => 'joe@test.com', + 'to' => 'bob@example.com', + 'subject' => 'Test', + 'text' => 'Test Data' } result = @mg_obj.post("#{@domain}/messages", data) result.to_h! - expect(result.body).to include("message") - expect(result.body).to include("id") + expect(result.body).to include('message') + expect(result.body).to include('id') end context 'when Unknown API error is raised' do before do - allow(Mailgun::Response).to receive(:new).and_raise(StandardError, "message") + allow(Mailgun::Response).to receive(:new).and_raise(StandardError, 'message') allow(JSON).to receive(:parse).and_raise('Unknown') end it 'adds Unknown API error to message' do - data = {'from' => 'joe@test.com', - 'to' => 'bob@example.com', - 'subject' => 'Test', - 'text' => 'Test Data'} + data = { 'from' => 'joe@test.com', + 'to' => 'bob@example.com', + 'subject' => 'Test', + 'text' => 'Test Data' } @mg_obj.post("#{@domain}/messages", data) - rescue Mailgun::CommunicationError => err - expect(err.message).to eq('message: Unknown API error') + rescue Mailgun::CommunicationError => e + expect(e.message).to eq('message: Unknown API error') else - fail + raise end end end describe 'The method put()' do before(:each) do - @mg_obj = Mailgun::UnitClient.new("lists") - @domain = "test.com" - @list_address = "mylist@test.com" - @member_address = "subscribee@test.com" + @mg_obj = Mailgun::UnitClient.new('lists') + @domain = 'test.com' + @list_address = 'mylist@test.com' + @member_address = 'subscribee@test.com' end it 'in this case, updates a member with the attributes in data.' do - data = {'subscribed' => false, - 'name' => 'Foo Bar'} + data = { 'subscribed' => false, + 'name' => 'Foo Bar' } result = @mg_obj.put("lists/#{@list_address}/members#{@member_address}", data) result.to_h! - expect(result.body).to include("member") - expect(result.body["member"]).to include("vars") - expect(result.body["member"]["vars"]).to include("age") - expect(result.body["member"]).to include("name") - expect(result.body["member"]).to include("subscribed") - expect(result.body["member"]).to include("address") - expect(result.body).to include("message") + expect(result.body).to include('member') + expect(result.body['member']).to include('vars') + expect(result.body['member']['vars']).to include('age') + expect(result.body['member']).to include('name') + expect(result.body['member']).to include('subscribed') + expect(result.body['member']).to include('address') + expect(result.body).to include('message') end - end describe 'The method get()' do before(:each) do - @mg_obj = Mailgun::UnitClient.new("bounces") - @domain = "test.com" + @mg_obj = Mailgun::UnitClient.new('bounces') + @domain = 'test.com' end it 'in this case, obtains a list of bounces for the domain, limit of 5, skipping the first 10.' do - query_string = {'skip' => '10', - 'limit' => '5'} + query_string = { 'skip' => '10', + 'limit' => '5' } result = @mg_obj.get("#{@domain}/bounces", query_string) result.to_h! - expect(result.body).to include("total_count") - expect(result.body).to include("items") + expect(result.body).to include('total_count') + expect(result.body).to include('items') end end describe 'The method delete()' do before(:each) do - @mg_obj = Mailgun::UnitClient.new("campaigns") - @domain = "test.com" + @mg_obj = Mailgun::UnitClient.new('campaigns') + @domain = 'test.com' end it 'issues a generic delete request.' do @@ -162,7 +163,7 @@ result.to_h! - expect(result.body).to include("message") - expect(result.body).to include("id") + expect(result.body).to include('message') + expect(result.body).to include('id') end end diff --git a/spec/unit/messages/batch_message_spec.rb b/spec/unit/messages/batch_message_spec.rb index a40f1d76..4684d4de 100644 --- a/spec/unit/messages/batch_message_spec.rb +++ b/spec/unit/messages/batch_message_spec.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'BatchMessage attribute readers' do it 'should be readable' do - @mb_client = Mailgun::UnitClient.new("messages") - @mb_obj = Mailgun::BatchMessage.new(@mb_client, "example.com") + @mb_client = Mailgun::UnitClient.new('messages') + @mb_obj = Mailgun::BatchMessage.new(@mb_client, 'example.com') expect(@mb_obj).to respond_to(:message_ids) expect(@mb_obj).to respond_to(:message) @@ -14,10 +16,9 @@ end describe 'The instantiation of Batch Message' do - before(:each) do - @mb_client = Mailgun::UnitClient.new("messages") - @mb_obj = Mailgun::BatchMessage.new(@mb_client, "example.com") + @mb_client = Mailgun::UnitClient.new('messages') + @mb_obj = Mailgun::BatchMessage.new(@mb_client, 'example.com') end it 'contains Message, which should be of type Hash and empty' do @@ -63,14 +64,14 @@ describe 'The method add_recipient' do before(:each) do - @mb_client = Mailgun::UnitClient.new("messages") - @mb_obj = Mailgun::BatchMessage.new(@mb_client, "example.com") + @mb_client = Mailgun::UnitClient.new('messages') + @mb_obj = Mailgun::BatchMessage.new(@mb_client, 'example.com') @address_1 = 'jane@example.com' - @variables_1 = {'first' => 'Jane', 'last' => 'Doe', 'tracking' => 'ABC123'} + @variables_1 = { 'first' => 'Jane', 'last' => 'Doe', 'tracking' => 'ABC123' } @address_2 = 'bob@example.com' - @variables_2 = {'first' => 'Bob', 'last' => 'Doe', 'tracking' => 'DEF123'} + @variables_2 = { 'first' => 'Bob', 'last' => 'Doe', 'tracking' => 'DEF123' } @address_3 = 'sam@example.com' - @variables_3 = {'first' => 'Sam', 'last' => 'Doe', 'tracking' => 'GHI123'} + @variables_3 = { 'first' => 'Sam', 'last' => 'Doe', 'tracking' => 'GHI123' } end context 'when from is present' do before(:each) do @@ -84,9 +85,9 @@ end expect(@mb_obj.counters[:recipients][recipient_type]).to eq(1000) - + @mb_obj.add_recipient(recipient_type, @address_1, @variables_1) - + expect(@mb_obj.counters[:recipients][recipient_type]).to eq(1) end @@ -127,7 +128,7 @@ @mb_obj.add_recipient(recipient_type, @address_1, @variables_1) @mb_obj.add_recipient(recipient_type, @address_2, @variables_2) @mb_obj.add_recipient(recipient_type, @address_3, @variables_3) - + expect(@mb_obj.recipient_variables[@address_1]).to eq(@variables_1) expect(@mb_obj.recipient_variables[@address_2]).to eq(@variables_2) expect(@mb_obj.recipient_variables[@address_3]).to eq(@variables_3) @@ -139,9 +140,8 @@ recipient_type = :to @mb_obj.add_recipient(recipient_type, @address_1, @variables_1) @mb_obj.add_recipient(recipient_type, @address_2, @variables_2) - expect(@mb_client).to receive(:fail) + expect(@mb_client).to receive(:raise) @mb_obj.finalize end end - end diff --git a/spec/unit/messages/message_builder_spec.rb b/spec/unit/messages/message_builder_spec.rb index 32837d7c..a9da276a 100644 --- a/spec/unit/messages/message_builder_spec.rb +++ b/spec/unit/messages/message_builder_spec.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'spec_helper' require 'stringio' describe 'MessageBuilder attribute readers' do it 'should be readable' do - @mb_obj = Mailgun::MessageBuilder.new() + @mb_obj = Mailgun::MessageBuilder.new expect(@mb_obj).to respond_to(:message) expect(@mb_obj).to respond_to(:counters) @@ -11,9 +13,8 @@ end describe 'The instantiation of MessageBuilder' do - before(:each) do - @mb_obj = Mailgun::MessageBuilder.new() + @mb_obj = Mailgun::MessageBuilder.new end it 'contains counters, which should be of type hash and contain several important counters' do @@ -39,7 +40,7 @@ before(:each) do @mb_obj = Mailgun::MessageBuilder.new @address = 'jane@example.com' - @variables = {'first' => 'Jane', 'last' => 'Doe'} + @variables = { 'first' => 'Jane', 'last' => 'Doe' } end it 'adds a "to" recipient type to the message body and counter is incremented' do @@ -55,7 +56,7 @@ recipient_type = :to @mb_obj.add_recipient(recipient_type, @address, {}) - expect(@mb_obj.message[recipient_type][0]).to eq("#{@address}") + expect(@mb_obj.message[recipient_type][0]).to eq(@address.to_s) expect(@mb_obj.counters[:recipients][recipient_type]).to eq(1) end end @@ -81,7 +82,7 @@ @mb_obj.add_recipient(recipient_type, @address, @variables) expect(@mb_obj.message[recipient_type]).to eq("'#{@variables['first']} #{@variables['last']}' <#{@address}>") - @mb_obj.counters[:recipients].each_value{|value| expect(value).to eq(0)} + @mb_obj.counters[:recipients].each_value { |value| expect(value).to eq(0) } end it 'ensures a random recipient type is added to the message body and counters are not incremented' do @@ -89,31 +90,34 @@ @mb_obj.add_recipient(recipient_type, @address, @variables) expect(@mb_obj.message[recipient_type][0]).to eq("'#{@variables['first']} #{@variables['last']}' <#{@address}>") - @mb_obj.counters[:recipients].each_value{|value| expect(value).to eq(0)} + @mb_obj.counters[:recipients].each_value { |value| expect(value).to eq(0) } end it 'adds too many to recipients and raises an exception.' do recipient_type = :to - expect{ + expect do 1001.times do @mb_obj.add_recipient(recipient_type, @address, @variables) - end }.to raise_error(Mailgun::ParameterError) + end + end.to raise_error(Mailgun::ParameterError) end it 'adds too many cc recipients and raises an exception.' do recipient_type = :cc - expect{ + expect do 1001.times do @mb_obj.add_recipient(recipient_type, @address, @variables) - end }.to raise_error(Mailgun::ParameterError) + end + end.to raise_error(Mailgun::ParameterError) end it 'adds too many bcc recipients and raises an exception.' do recipient_type = :bcc - expect{ + expect do 1001.times do @mb_obj.add_recipient(recipient_type, @address, @variables) - end }.to raise_error(Mailgun::ParameterError) + end + end.to raise_error(Mailgun::ParameterError) end end @@ -195,7 +199,6 @@ expect(@mb_obj.message['amp-html']).to eq(the_text) end end - describe 'The method set_from_address' do it 'warns of set_from_address deprecation' do @@ -221,7 +224,7 @@ the_from_address = 'test@mailgun.com' the_first_name = 'Magilla' the_last_name = 'Gorilla' - @mb_obj.from(the_from_address, {'first' => the_first_name, 'last' => the_last_name}) + @mb_obj.from(the_from_address, { 'first' => the_first_name, 'last' => the_last_name }) expect(@mb_obj.message[:from]).to eq(["'#{the_first_name} #{the_last_name}' <#{the_from_address}>"]) end @@ -229,7 +232,7 @@ it 'sets the from address with full name metadata' do the_from_address = 'test@mailgun.com' full_name = 'Magilla Gorilla' - @mb_obj.from(the_from_address, {'full_name' => full_name}) + @mb_obj.from(the_from_address, { 'full_name' => full_name }) expect(@mb_obj.message[:from]).to eq(["'#{full_name}' <#{the_from_address}>"]) end @@ -238,7 +241,7 @@ the_from_address = 'test@mailgun.com' full_name = 'Magilla Gorilla' first_name = 'Magilla' - expect{@mb_obj.from(the_from_address, {'full_name' => full_name, 'first' => first_name})}.to raise_error(Mailgun::ParameterError) + expect { @mb_obj.from(the_from_address, { 'full_name' => full_name, 'first' => first_name }) }.to raise_error(Mailgun::ParameterError) end end @@ -247,20 +250,19 @@ @mb_obj = Mailgun::MessageBuilder.new end it 'adds a few file paths to the message object' do - - file1 = File.dirname(__FILE__) + "/sample_data/mailgun_icon.png" - file2 = File.dirname(__FILE__) + "/sample_data/rackspace_logo.jpg" + file1 = "#{File.dirname(__FILE__)}/sample_data/mailgun_icon.png" + file2 = "#{File.dirname(__FILE__)}/sample_data/rackspace_logo.jpg" file_paths = [file1, file2] - file_paths.each {|item| @mb_obj.add_attachment(item)} + file_paths.each { |item| @mb_obj.add_attachment(item) } expect(@mb_obj.message[:attachment].length).to eq(2) end it 'adds file-like objects to the message object' do io = StringIO.new - io << File.binread(File.dirname(__FILE__) + "/sample_data/mailgun_icon.png") + io << File.binread("#{File.dirname(__FILE__)}/sample_data/mailgun_icon.png") @mb_obj.add_attachment io, 'cool_attachment.png' @@ -271,7 +273,7 @@ context 'when attachment has unknown type' do it 'sets content type application/octet-stream for attachment' do - file = File.dirname(__FILE__) + "/sample_data/unknown.type" + file = "#{File.dirname(__FILE__)}/sample_data/unknown.type" @mb_obj.add_attachment(file) @@ -285,12 +287,12 @@ @mb_obj = Mailgun::MessageBuilder.new end it 'adds a few file paths to the message object' do - file1 = File.dirname(__FILE__) + "/sample_data/mailgun_icon.png" - file2 = File.dirname(__FILE__) + "/sample_data/rackspace_logo.jpg" + file1 = "#{File.dirname(__FILE__)}/sample_data/mailgun_icon.png" + file2 = "#{File.dirname(__FILE__)}/sample_data/rackspace_logo.jpg" file_paths = [file1, file2] - file_paths.each {|item| @mb_obj.add_inline_image(item)} + file_paths.each { |item| @mb_obj.add_inline_image(item) } expect(@mb_obj.message[:inline].length).to eq(2) end @@ -313,7 +315,7 @@ end it 'sets the message list_unsubscribe if called with many list_unsubscribe parameters' do - unsubscribe_to = %w(http://example.com/stop-hassle mailto:stop-hassle@example.com) + unsubscribe_to = %w[http://example.com/stop-hassle mailto:stop-hassle@example.com] @mb_obj.list_unsubscribe(*unsubscribe_to) expect(@mb_obj.message['h:List-Unsubscribe']).to eq( unsubscribe_to.map { |var| "<#{var}>" }.join(',') @@ -336,30 +338,30 @@ it 'turns on test mode with boolean true' do @mb_obj.test_mode(true) - expect(@mb_obj.message["o:testmode"][0]).to eq("yes") + expect(@mb_obj.message['o:testmode'][0]).to eq('yes') end it 'turns on test mode with string true' do - @mb_obj.test_mode("true") + @mb_obj.test_mode('true') - expect(@mb_obj.message["o:testmode"][0]).to eq("yes") + expect(@mb_obj.message['o:testmode'][0]).to eq('yes') end it 'turns off test mode with boolean false' do @mb_obj.test_mode(false) - expect(@mb_obj.message["o:testmode"][0]).to eq("no") + expect(@mb_obj.message['o:testmode'][0]).to eq('no') end it 'turns off test mode with string false' do - @mb_obj.test_mode("false") + @mb_obj.test_mode('false') - expect(@mb_obj.message["o:testmode"][0]).to eq("no") + expect(@mb_obj.message['o:testmode'][0]).to eq('no') end it 'does not allow multiple values' do - @mb_obj.test_mode("false") - @mb_obj.test_mode("true") - @mb_obj.test_mode("false") + @mb_obj.test_mode('false') + @mb_obj.test_mode('true') + @mb_obj.test_mode('false') - expect(@mb_obj.message["o:testmode"].length).to eq(1) - expect(@mb_obj.message["o:testmode"][0]).to eq("no") + expect(@mb_obj.message['o:testmode'].length).to eq(1) + expect(@mb_obj.message['o:testmode'][0]).to eq('no') end end @@ -378,30 +380,30 @@ it 'turns on dkim with boolean true' do @mb_obj.dkim(true) - expect(@mb_obj.message["o:dkim"][0]).to eq("yes") + expect(@mb_obj.message['o:dkim'][0]).to eq('yes') end it 'turns on dkim with string true' do - @mb_obj.dkim("true") + @mb_obj.dkim('true') - expect(@mb_obj.message["o:dkim"][0]).to eq("yes") + expect(@mb_obj.message['o:dkim'][0]).to eq('yes') end it 'turns off dkim with boolean false' do @mb_obj.dkim(false) - expect(@mb_obj.message["o:dkim"][0]).to eq("no") + expect(@mb_obj.message['o:dkim'][0]).to eq('no') end it 'turns off dkim with string false' do - @mb_obj.dkim("false") + @mb_obj.dkim('false') - expect(@mb_obj.message["o:dkim"][0]).to eq("no") + expect(@mb_obj.message['o:dkim'][0]).to eq('no') end it 'does not allow multiple values' do - @mb_obj.dkim("false") - @mb_obj.dkim("true") - @mb_obj.dkim("false") + @mb_obj.dkim('false') + @mb_obj.dkim('true') + @mb_obj.dkim('false') - expect(@mb_obj.message["o:dkim"].length).to eq(1) - expect(@mb_obj.message["o:dkim"][0]).to eq("no") + expect(@mb_obj.message['o:dkim'].length).to eq(1) + expect(@mb_obj.message['o:dkim'][0]).to eq('no') end end @@ -412,22 +414,23 @@ it 'adds a campaign ID to the message' do @mb_obj.add_campaign_id('My-Campaign-Id-1') - expect(@mb_obj.message["o:campaign"][0]).to eq ("My-Campaign-Id-1") + expect(@mb_obj.message['o:campaign'][0]).to eq('My-Campaign-Id-1') end it 'adds a few more campaign IDs to the message' do @mb_obj.add_campaign_id('My-Campaign-Id-1') @mb_obj.add_campaign_id('My-Campaign-Id-2') @mb_obj.add_campaign_id('My-Campaign-Id-3') - expect(@mb_obj.message["o:campaign"][0]).to eq("My-Campaign-Id-1") - expect(@mb_obj.message["o:campaign"][1]).to eq("My-Campaign-Id-2") - expect(@mb_obj.message["o:campaign"][2]).to eq("My-Campaign-Id-3") + expect(@mb_obj.message['o:campaign'][0]).to eq('My-Campaign-Id-1') + expect(@mb_obj.message['o:campaign'][1]).to eq('My-Campaign-Id-2') + expect(@mb_obj.message['o:campaign'][2]).to eq('My-Campaign-Id-3') end it 'adds too many campaign IDs to the message' do - expect{ + expect do 10.times do @mb_obj.add_campaign_id('Test-Campaign-ID') - end }.to raise_error(Mailgun::ParameterError) + end + end.to raise_error(Mailgun::ParameterError) end end @@ -438,22 +441,23 @@ it 'adds a tag to the message' do @mb_obj.add_tag('My-Tag-1') - expect(@mb_obj.message["o:tag"][0]).to eq("My-Tag-1") + expect(@mb_obj.message['o:tag'][0]).to eq('My-Tag-1') end it 'adds a few more tags to the message' do @mb_obj.add_tag('My-Tag-1') @mb_obj.add_tag('My-Tag-2') @mb_obj.add_tag('My-Tag-3') - expect(@mb_obj.message["o:tag"][0]).to eq("My-Tag-1") - expect(@mb_obj.message["o:tag"][1]).to eq("My-Tag-2") - expect(@mb_obj.message["o:tag"][2]).to eq("My-Tag-3") + expect(@mb_obj.message['o:tag'][0]).to eq('My-Tag-1') + expect(@mb_obj.message['o:tag'][1]).to eq('My-Tag-2') + expect(@mb_obj.message['o:tag'][2]).to eq('My-Tag-3') end it 'adds too many tags to the message' do - expect{ + expect do 12.times do @mb_obj.add_tag('My-Tag') - end }.to raise_error(Mailgun::ParameterError) + end + end.to raise_error(Mailgun::ParameterError) end end @@ -472,20 +476,20 @@ it 'enables/disables open tracking on a per message basis.' do @mb_obj.track_opens('Yes') - expect(@mb_obj.message["o:tracking-opens"]).to eq("yes") - expect(@mb_obj.message["o:tracking"]).to eq(["yes"]) + expect(@mb_obj.message['o:tracking-opens']).to eq('yes') + expect(@mb_obj.message['o:tracking']).to eq(['yes']) @mb_obj.track_opens('No') - expect(@mb_obj.message["o:tracking-opens"]).to eq("no") + expect(@mb_obj.message['o:tracking-opens']).to eq('no') @mb_obj.track_opens(true) - expect(@mb_obj.message["o:tracking-opens"]).to eq("yes") + expect(@mb_obj.message['o:tracking-opens']).to eq('yes') @mb_obj.track_opens(false) - expect(@mb_obj.message["o:tracking-opens"]).to eq("no") + expect(@mb_obj.message['o:tracking-opens']).to eq('no') end end @@ -504,24 +508,24 @@ it 'enables/disables click tracking on a per message basis.' do @mb_obj.track_clicks('Yes') - expect(@mb_obj.message["o:tracking-clicks"]).to eq("yes") - expect(@mb_obj.message["o:tracking"]).to eq(["yes"]) + expect(@mb_obj.message['o:tracking-clicks']).to eq('yes') + expect(@mb_obj.message['o:tracking']).to eq(['yes']) @mb_obj.track_clicks('No') - expect(@mb_obj.message["o:tracking-clicks"]).to eq("no") + expect(@mb_obj.message['o:tracking-clicks']).to eq('no') @mb_obj.track_clicks(true) - expect(@mb_obj.message["o:tracking-clicks"]).to eq("yes") + expect(@mb_obj.message['o:tracking-clicks']).to eq('yes') @mb_obj.track_clicks(false) - expect(@mb_obj.message["o:tracking-clicks"]).to eq("no") + expect(@mb_obj.message['o:tracking-clicks']).to eq('no') @mb_obj.track_clicks('html') - expect(@mb_obj.message["o:tracking-clicks"]).to eq("html") + expect(@mb_obj.message['o:tracking-clicks']).to eq('html') end context 'when unexpected value is provided' do @@ -547,7 +551,7 @@ it 'defines a time/date to deliver a message in RFC2822 format.' do @mb_obj.deliver_at('October 25, 2013 10:00PM CST') - expect(@mb_obj.message["o:deliverytime"][0]).to eq("Fri, 25 Oct 2013 22:00:00 -0600") + expect(@mb_obj.message['o:deliverytime'][0]).to eq('Fri, 25 Oct 2013 22:00:00 -0600') end end @@ -566,8 +570,8 @@ it 'accepts valid JSON and appends as data to the message.' do @mb_obj.header('my-data', '{"key":"value"}') - expect(@mb_obj.message["h:my-data"]).to be_kind_of(String) - expect(@mb_obj.message["h:my-data"].to_s).to eq('{"key":"value"}') + expect(@mb_obj.message['h:my-data']).to be_kind_of(String) + expect(@mb_obj.message['h:my-data'].to_s).to eq('{"key":"value"}') end end @@ -578,23 +582,23 @@ it 'accepts valid JSON and stores it as message[param].' do @mb_obj.variable('my-data', '{"key":"value"}') - expect(@mb_obj.message["v:my-data"]).to be_kind_of(String) - expect(@mb_obj.message["v:my-data"].to_s).to eq('{"key":"value"}') + expect(@mb_obj.message['v:my-data']).to be_kind_of(String) + expect(@mb_obj.message['v:my-data'].to_s).to eq('{"key":"value"}') end it 'accepts a hash and appends as data to the message.' do - data = {'key' => 'value'} + data = { 'key' => 'value' } @mb_obj.variable('my-data', data) - expect(@mb_obj.message["v:my-data"]).to be_kind_of(String) - expect(@mb_obj.message["v:my-data"].to_s).to eq('{"key":"value"}') + expect(@mb_obj.message['v:my-data']).to be_kind_of(String) + expect(@mb_obj.message['v:my-data'].to_s).to eq('{"key":"value"}') end it 'accepts string values' do data = 'String Value.' @mb_obj.variable('my-data', data) - expect(@mb_obj.message["v:my-data"]).to be_kind_of(String) - expect(@mb_obj.message["v:my-data"].to_s).to eq('String Value.') + expect(@mb_obj.message['v:my-data']).to be_kind_of(String) + expect(@mb_obj.message['v:my-data'].to_s).to eq('String Value.') end end @@ -605,7 +609,7 @@ it 'adds an undefined parameter to the message.' do @mb_obj.add_custom_parameter('h:my-sweet-header', 'datagoeshere') - expect(@mb_obj.message["h:my-sweet-header"][0]).to eq("datagoeshere") + expect(@mb_obj.message['h:my-sweet-header'][0]).to eq('datagoeshere') end end @@ -630,16 +634,16 @@ it 'correctly clears the Message-Id header when passed nil' do @mb_obj.message_id(nil) - expect(@mb_obj.message.has_key?('h:Message-Id')).to eq(false) + expect(@mb_obj.message.key?('h:Message-Id')).to eq(false) end it 'correctly sets the Message-Id header when passed an empty string' do @mb_obj.message_id(@the_message_id) - expect(@mb_obj.message.has_key?('h:Message-Id')).to eq(true) + expect(@mb_obj.message.key?('h:Message-Id')).to eq(true) @mb_obj.message_id('') - expect(@mb_obj.message.has_key?('h:Message-Id')).to eq(false) + expect(@mb_obj.message.key?('h:Message-Id')).to eq(false) end end @@ -672,11 +676,11 @@ it 'it deletes `template` key from the message' do @mb_obj.template('template.name') - expect(@mb_obj.message.has_key?('template')).to eq(true) + expect(@mb_obj.message.key?('template')).to eq(true) @mb_obj.template - expect(@mb_obj.message.has_key?('template')).to eq(false) + expect(@mb_obj.message.key?('template')).to eq(false) end end end @@ -710,11 +714,11 @@ it 'it deletes `t:version` key from the message' do @mb_obj.template_version('version') - expect(@mb_obj.message.has_key?('t:version')).to eq(true) + expect(@mb_obj.message.key?('t:version')).to eq(true) @mb_obj.template_version - expect(@mb_obj.message.has_key?('t:version')).to eq(false) + expect(@mb_obj.message.key?('t:version')).to eq(false) end end end @@ -727,18 +731,18 @@ it 'enables/disables rendering in the text part of the message in case of template sending' do @mb_obj.template_text('Yes') - expect(@mb_obj.message["t:text"]).to eq("yes") + expect(@mb_obj.message['t:text']).to eq('yes') @mb_obj.template_text('No') - expect(@mb_obj.message["t:text"]).to eq("no") + expect(@mb_obj.message['t:text']).to eq('no') @mb_obj.template_text(true) - expect(@mb_obj.message["t:text"]).to eq("yes") + expect(@mb_obj.message['t:text']).to eq('yes') @mb_obj.template_text(false) - expect(@mb_obj.message["t:text"]).to eq("no") + expect(@mb_obj.message['t:text']).to eq('no') end end diff --git a/spec/unit/railgun/content_type_spec.rb b/spec/unit/railgun/content_type_spec.rb index 8a048d1e..5c0c139a 100644 --- a/spec/unit/railgun/content_type_spec.rb +++ b/spec/unit/railgun/content_type_spec.rb @@ -1,40 +1,41 @@ +# frozen_string_literal: true + require 'spec_helper' require 'mailgun' require 'railgun' describe 'extract_body' do - - let(:text_mail_option) { + let(:text_mail_option) do { - from: 'bob@example.com', - to: 'sally@example.com', - subject: 'RAILGUN TEST SAMPLE', - body: text_content, - content_type: 'text/plain', + from: 'bob@example.com', + to: 'sally@example.com', + subject: 'RAILGUN TEST SAMPLE', + body: text_content, + content_type: 'text/plain' } - } + end let(:text_content) { '[TEST] Hello, world.' } - let(:html_mail_option) { + let(:html_mail_option) do { - from: 'bob@example.com', - to: 'sally@example.com', - subject: 'RAILGUN TEST SAMPLE', - body: html_content, - content_type: 'text/html', + from: 'bob@example.com', + to: 'sally@example.com', + subject: 'RAILGUN TEST SAMPLE', + body: html_content, + content_type: 'text/html' } - } + end let(:html_content) { '

[TEST]


Hello, world!' } - let(:amp_mail_option) { + let(:amp_mail_option) do { - from: 'bob@example.com', - to: 'sally@example.com', - subject: 'RAILGUN TEST SAMPLE', - body: amp_content, - content_type: 'text/x-amp-html', + from: 'bob@example.com', + to: 'sally@example.com', + subject: 'RAILGUN TEST SAMPLE', + body: amp_content, + content_type: 'text/x-amp-html' } - } + end let(:amp_content) { '

[TEST]


Hello from AMP!' } context 'with ' do @@ -67,7 +68,7 @@ let(:amp_mail) { Mail.new(amp_mail_option) } before do - @sample_mail = Mail::Part.new(content_type: "multipart/alternative") + @sample_mail = Mail::Part.new(content_type: 'multipart/alternative') @sample_mail.add_part text_mail @sample_mail.add_part amp_mail @sample_mail.add_part html_mail diff --git a/spec/unit/railgun/mailer_spec.rb b/spec/unit/railgun/mailer_spec.rb index a0c54af3..8c98a235 100644 --- a/spec/unit/railgun/mailer_spec.rb +++ b/spec/unit/railgun/mailer_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'json' require 'logger' require 'spec_helper' @@ -15,42 +17,40 @@ class UnitTestMailer < ActionMailer::Base def plain_message(address, subject, headers) headers(headers) mail(to: address, subject: subject) do |format| - format.text { render plain: "Test!" } - format.html { render html: "

Test!

".html_safe } + format.text { render plain: 'Test!' } + format.html { render html: '

Test!

'.html_safe } end end def message_with_attachment(address, subject) attachments['info.txt'] = { - :content => File.read('docs/railgun/Overview.md'), - :mime_type => 'text/plain', + content: File.read('docs/railgun/Overview.md'), + mime_type: 'text/plain' } mail(to: address, subject: subject) do |format| - format.text { render plain: "Test!" } - format.html { render html: "

Test!

".html_safe } + format.text { render plain: 'Test!' } + format.html { render html: '

Test!

'.html_safe } end end def message_with_template(address, subject, template_name) mail(to: address, subject: subject, template: template_name) do |format| - format.text { render plain: "Test!" } + format.text { render plain: 'Test!' } end end def message_with_domain(address, subject, domain) mail(to: address, subject: subject, domain: domain) do |format| - format.text { render plain: "Test!" } + format.text { render plain: 'Test!' } end end - end describe 'Railgun::Mailer' do - it 'has a mailgun_client property which returns a Mailgun::Client' do config = { - api_key: {}, - domain: {} + api_key: {}, + domain: {} } @mailer_obj = Railgun::Mailer.new(config) @@ -60,18 +60,18 @@ def message_with_domain(address, subject, domain) context 'when config does not have api_key or domain' do it 'raises configuration error' do config = { - api_key: {} + api_key: {} } - expect { Railgun::Mailer.new(config) }.to raise_error(Railgun::ConfigurationError) + expect { Railgun::Mailer.new(config) }.to raise_error(Railgun::ConfigurationError) end end context 'when fake_message_send is present in config' do it 'enables test mode' do config = { - api_key: {}, - domain: {}, + api_key: {}, + domain: {}, fake_message_send: true } client_double = double(Mailgun::Client) @@ -100,7 +100,7 @@ def message_with_domain(address, subject, domain) it 'adds options to message body' do message = UnitTestMailer.plain_message('test@example.org', '', {}) message.mailgun_options ||= { - 'tracking-opens' => 'true', + 'tracking-opens' => 'true' } body = Railgun.transform_for_mailgun(message) @@ -124,14 +124,14 @@ def message_with_domain(address, subject, domain) it 'adds variables to message body' do message = UnitTestMailer.plain_message('test@example.org', '', {}) message.mailgun_variables ||= { - 'user' => {:id => '1', :name => 'tstark'}, + 'user' => { id: '1', name: 'tstark' } } body = Railgun.transform_for_mailgun(message) expect(body).to include('v:user') - var_body = JSON.load(body['v:user']) + var_body = JSON.parse(body['v:user']) expect(var_body).to include('id') expect(var_body).to include('name') expect(var_body['id']).to eq('1') @@ -141,7 +141,7 @@ def message_with_domain(address, subject, domain) it 'adds headers to message body' do message = UnitTestMailer.plain_message('test@example.org', '', {}) message.mailgun_headers ||= { - 'x-unit-test' => 'true', + 'x-unit-test' => 'true' } body = Railgun.transform_for_mailgun(message) @@ -152,8 +152,8 @@ def message_with_domain(address, subject, domain) it 'adds headers to message body from mailer' do message = UnitTestMailer.plain_message('test@example.org', '', { - 'x-unit-test-2' => 'true', - }) + 'x-unit-test-2' => 'true' + }) body = Railgun.transform_for_mailgun(message) @@ -163,20 +163,20 @@ def message_with_domain(address, subject, domain) it 'properly handles headers that are passed as separate POST params' do message = UnitTestMailer.plain_message('test@example.org', 'Test!', { - # `From`, `To`, and `Subject` are set on the envelope, so they should be ignored as headers - 'From' => 'units@example.net', - 'To' => 'user@example.com', - 'Subject' => 'This should disappear', - # If `Bcc` or `Cc` are set as headers, they should be carried over as POST params, not headers - 'Bcc' => ['list@example.org'], - 'Cc' => ['admin@example.com'], - # This is an arbitrary header and should be carried over properly - 'X-Source' => 'unit tests', - }) + # `From`, `To`, and `Subject` are set on the envelope, so they should be ignored as headers + 'From' => 'units@example.net', + 'To' => 'user@example.com', + 'Subject' => 'This should disappear', + # If `Bcc` or `Cc` are set as headers, they should be carried over as POST params, not headers + 'Bcc' => ['list@example.org'], + 'Cc' => ['admin@example.com'], + # This is an arbitrary header and should be carried over properly + 'X-Source' => 'unit tests' + }) body = Railgun.transform_for_mailgun(message) - ['From', 'To', 'Subject'].each do |header| + %w[From To Subject].each do |header| expect(body).not_to include("h:#{header}") end @@ -202,20 +202,20 @@ def message_with_domain(address, subject, domain) } end body = Railgun.transform_for_mailgun(message) - expect(body["v:my-data"]).to be_kind_of(String) - expect(body["v:my-data"].to_s).to eq('{"key":"value"}') + expect(body['v:my-data']).to be_kind_of(String) + expect(body['v:my-data'].to_s).to eq('{"key":"value"}') end it 'accepts a hash and appends as data to the message.' do message = UnitTestMailer.plain_message('test@example.org', '', {}).tap do |message| message.mailgun_variables = { - 'my-data' => {'key' => 'value'} + 'my-data' => { 'key' => 'value' } } end body = Railgun.transform_for_mailgun(message) - expect(body["v:my-data"]).to be_kind_of(String) - expect(body["v:my-data"].to_s).to eq('{"key":"value"}') + expect(body['v:my-data']).to be_kind_of(String) + expect(body['v:my-data'].to_s).to eq('{"key":"value"}') end it 'accepts string values' do @@ -226,8 +226,8 @@ def message_with_domain(address, subject, domain) end body = Railgun.transform_for_mailgun(message) - expect(body["v:my-data"]).to be_kind_of(String) - expect(body["v:my-data"].to_s).to eq('String Value.') + expect(body['v:my-data']).to be_kind_of(String) + expect(body['v:my-data'].to_s).to eq('String Value.') end end @@ -251,13 +251,13 @@ def message_with_domain(address, subject, domain) it 'ignores `reply-to` in headers' do message = UnitTestMailer.plain_message('test@example.org', '', { - 'reply-to' => 'user@example.com', - }) + 'reply-to' => 'user@example.com' + }) message.mailgun_headers = { - 'Reply-To' => 'administrator@example.org', + 'Reply-To' => 'administrator@example.org' } - message.headers({'REPLY-TO' => 'admin@example.net'}) - message.reply_to = "dude@example.com.au" + message.headers({ 'REPLY-TO' => 'admin@example.net' }) + message.reply_to = 'dude@example.com.au' body = Railgun.transform_for_mailgun(message) expect(body).to include('h:reply-to') @@ -267,12 +267,12 @@ def message_with_domain(address, subject, domain) it 'ignores `mime-version` in headers' do message = UnitTestMailer.plain_message('test@example.org', '', { - 'mime-version' => '1.0', - }) + 'mime-version' => '1.0' + }) message.mailgun_headers = { - 'Mime-Version' => '1.1', + 'Mime-Version' => '1.1' } - message.headers({'MIME-VERSION' => '1.2'}) + message.headers({ 'MIME-VERSION' => '1.2' }) body = Railgun.transform_for_mailgun(message) expect(body).not_to include('h:mime-version') @@ -280,32 +280,32 @@ def message_with_domain(address, subject, domain) it 'treats `headers()` names as case-insensitve' do message = UnitTestMailer.plain_message('test@example.org', '', { - 'X-BIG-VALUE' => 1, - }) + 'X-BIG-VALUE' => 1 + }) body = Railgun.transform_for_mailgun(message) expect(body).to include('h:x-big-value') - expect(body['h:x-big-value']).to eq("1") + expect(body['h:x-big-value']).to eq('1') end it 'treats `mailgun_headers` names as case-insensitive' do message = UnitTestMailer.plain_message('test@example.org', '', {}) message.mailgun_headers = { - 'X-BIG-VALUE' => 1, + 'X-BIG-VALUE' => 1 } body = Railgun.transform_for_mailgun(message) expect(body).to include('h:x-big-value') - expect(body['h:x-big-value']).to eq("1") + expect(body['h:x-big-value']).to eq('1') end it 'handles multi-value, mixed case headers correctly' do message = UnitTestMailer.plain_message('test@example.org', '', {}) message.headers({ - 'x-neat-header' => 'foo', - 'X-Neat-Header' => 'bar', - 'X-NEAT-HEADER' => 'zoop', - }) + 'x-neat-header' => 'foo', + 'X-Neat-Header' => 'bar', + 'X-NEAT-HEADER' => 'zoop' + }) body = Railgun.transform_for_mailgun(message) expect(body).to include('h:x-neat-header')