diff --git a/.codeclimate.yml b/.codeclimate.yml new file mode 100644 index 00000000..71d52ceb --- /dev/null +++ b/.codeclimate.yml @@ -0,0 +1,21 @@ +--- +engines: + duplication: + enabled: true + config: + languages: + - ruby + fixme: + enabled: true + rubocop: + enabled: true + bundler-audit: + enabled: true +ratings: + paths: + - "**.rb" +exclude_paths: +- examples/ +- spec/ +- test/ +- gemfiles/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 36934fe9..a8e40475 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,22 @@ # Change Log All notable changes to this project will be documented in this file. +## [5.3.0] - 2018-10-12 ## +### Added +- [PR #300](https://github.com/sendgrid/sendgrid-ruby/pull/300): Support for Dynamic Templates. Big thanks to [@nedcampion](https://github.com/nedcampion) for the PR! +- [PR #178](https://github.com/sendgrid/sendgrid-ruby/pull/178): Convert key/value arguments to CustomArgs to strings. Big thanks to [@sitaramshelke](https://github.com/sitaramshelke) for the PR! +- [PR #258](https://github.com/sendgrid/sendgrid-ruby/pull/258): Added unittest to check for specific repo files. Big thanks to [@mptap](https://github.com/mptap) for the PR! +- [PR #255](https://github.com/sendgrid/sendgrid-ruby/pull/255): Add a unittest to check the license.md file date range. Big thanks to [@prashuchaudhary](https://github.com/prashuchaudhary) for the PR! +- [PR #181](https://github.com/sendgrid/sendgrid-ruby/pull/181): Add Docker. Big thanks to [@shrivara](https://github.com/shrivara) for the PR! +- [PR #248](https://github.com/sendgrid/sendgrid-ruby/pull/248): Added .codeclimate.yml. Big thanks to [@proton](https://github.com/proton) for the PR! +- [PR #260](https://github.com/sendgrid/sendgrid-ruby/pull/260): Update ruby-http-client dependency to support v3.3.0. Big thanks to [@mptap](https://github.com/mptap) for the PR! +- [PR #304](https://github.com/sendgrid/sendgrid-ruby/pull/304): Readability update for documentation. Big thanks to [@af4ro](https://github.com/af4ro) for the PR! +- [PR #306](https://github.com/sendgrid/sendgrid-ruby/pull/306): Update example to work in Rails console. Big thanks to [@RogerPodacter](https://github.com/RogerPodacter) for the PR! + +### Fixes +- [PR #252](https://github.com/sendgrid/sendgrid-ruby/pull/252): Update LICENSE, set correct year. Big thanks to [@pushkyn](https://github.com/pushkyn) for the PR! +- [PR #257](https://github.com/sendgrid/sendgrid-ruby/pull/257): README.md typo fix. Big thanks to [@shucon](https://github.com/shucon) for the PR! + ## [5.2.0] - 2017-10-30 ## ### Added - PR #234: Helpers for email statistics - global, category, subuser diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9f9ae7c5..15e3be27 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,13 +1,19 @@ Hello! Thank you for choosing to help contribute to one of the SendGrid open source libraries. There are many ways you can contribute and help is always welcome. We simply ask that you follow the following contribution policies. -- [CLAs and CCLAs](#cla) -- [Roadmap & Milestones](#roadmap) +- [CLAs and CCLAs](#clas-and-cclas) - [Feature Request](#feature-request) - [Submit a Bug Report](#submit-a-bug-report) + - [Please use our Bug Report Template](#please-use-our-bug-report-template) - [Improvements to the Codebase](#improvements-to-the-codebase) -- [Understanding the Code Base](#understanding-the-codebase) + - [Development Environment](#development-environment) + - [Install and Run Locally](#install-and-run-locally) + - [Prerequisites](#prerequisites) + - [Initial setup:](#initial-setup) +- [Environment Variables](#environment-variables) + - [Execute:](#execute) +- [Understanding the Code Base](#understanding-the-code-base) - [Testing](#testing) -- [Style Guidelines & Naming Conventions](#style-guidelines-and-naming-conventions) +- [Style Guidelines & Naming Conventions](#style-guidelines--naming-conventions) - [Creating a Pull Request](#creating-a-pull-request) @@ -83,7 +89,7 @@ We welcome direct contributions to the sendgrid-ruby code base. Thank you! bundle install ``` -## Environment Variables +### Environment Variables First, get your free SendGrid account [here](https://sendgrid.com/free?source=sendgrid-ruby). @@ -163,8 +169,10 @@ Please run your code through: ```bash # Clone your fork of the repo into the current directory git clone https://github.com/sendgrid/sendgrid-ruby + # Navigate to the newly cloned directory cd sendgrid-ruby + # Assign the original repo to a remote called "upstream" git remote add upstream https://github.com/sendgrid/sendgrid-ruby ``` diff --git a/LICENSE.txt b/LICENSE.txt index 32b24e29..24411a03 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2014-2017 SendGrid, Inc. +Copyright (c) 2014-2018 SendGrid, Inc. MIT License diff --git a/README.md b/README.md index 371f65bd..867328e6 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Version 3.X.X+ of this library provides full support for all SendGrid [Web API v This library represents the beginning of a new path for SendGrid. We want this library to be community driven and SendGrid led. We need your help to realize this goal. To help make sure we are building the right things in the right order, we ask that you create [issues](https://github.com/sendgrid/sendgrid-ruby/issues) and [pull requests](https://github.com/sendgrid/sendgrid-ruby/blob/master/CONTRIBUTING.md) or simply upvote or comment on existing issues or pull requests. -Please browse the rest of this README for further detail. +Please browse the rest of this README for further details. We appreciate your continued support, thank you! @@ -83,16 +83,17 @@ The following is the minimum needed code to send an email with the [/mail/send H require 'sendgrid-ruby' include SendGrid -from = Email.new(email: 'test@example.com') -to = Email.new(email: 'test@example.com') +from = SendGrid::Email.new(email: 'test@example.com') +to = SendGrid::Email.new(email: 'test@example.com') subject = 'Sending with SendGrid is Fun' -content = Content.new(type: 'text/plain', value: 'and easy to do anywhere, even with Ruby') +content = SendGrid::Content.new(type: 'text/plain', value: 'and easy to do anywhere, even with Ruby') mail = SendGrid::Mail.new(from, subject, to, content) sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) response = sg.client.mail._('send').post(request_body: mail.to_json) puts response.status_code puts response.body +puts response.parsed_body puts response.headers ``` @@ -131,6 +132,7 @@ sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) response = sg.client.mail._("send").post(request_body: data) puts response.status_code puts response.body +puts response.parsed_body puts response.headers ``` @@ -142,6 +144,7 @@ sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) response = sg.client.suppression.bounces.get() puts response.status_code puts response.body +puts response.parsed_body puts response.headers ``` @@ -153,6 +156,7 @@ sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) response = sg.client._("suppression/bounces").get() puts response.status_code puts response.body +puts response.parsed_body puts response.headers ``` diff --git a/USE_CASES.md b/USE_CASES.md index b60726b2..a0ce96d0 100644 --- a/USE_CASES.md +++ b/USE_CASES.md @@ -3,6 +3,7 @@ This documentation provides examples for specific use cases. Please [open an iss # Table of Contents * [Transactional Templates](#transactional-templates) +* [Legacy Templates](#legacy-templates) * [How to Setup a Domain Whitelabel](#domain-whitelabel) * [How to View Email Statistics](#email-statistics) @@ -13,6 +14,106 @@ For this example, we assume you have created a [transactional template](https:// Template ID (replace with your own): +```text +d-2c214ac919e84170b21855cc129b4a5f +``` +Email Subject: +```text +{{subject}} +``` + +Template Body: + +```html + + + + + + Hello {{name}}, +

+ I'm glad you are trying out the template feature! +

+ I hope you are having a great day in {{city}} :) +

+ + +``` + +## With Mail Helper Class +```ruby +require 'sendgrid-ruby' +include SendGrid + +mail = Mail.new +mail.from = Email.new(email: 'test@example.com') +personalization = Personalization.new +personalization.add_to(Email.new(email: 'test@example.com')) +personalization.add_dynamic_template_data({ + "subject" => "Testing Templates", + "name" => "Example User", + "city" => "Denver" + }) +mail.add_personalization(personalization) +mail.template_id = 'd-2c214ac919e84170b21855cc129b4a5f' + +sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) +begin + response = sg.client.mail._("send").post(request_body: mail.to_json) +rescue Exception => e + puts e.message +end +puts response.status_code +puts response.body +puts response.parsed_body +puts response.headers +``` + +## Without Mail Helper Class + +```ruby +require 'sendgrid-ruby' +include SendGrid + +data = JSON.parse('{ + "personalizations": [ + { + "to": [ + { + "email": "test@example.com" + } + ], + "dynamic_template_data": { + "subject": "Testing Templates", + "name": "Example User", + "city": "Denver" + } + } + ], + "from": { + "email": "test@example.com" + }, + "template_id": "d-2c214ac919e84170b21855cc129b4a5f" +}') +sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) +begin + response = sg.client.mail._("send").post(request_body: data) +rescue Exception => e + puts e.message +end +puts response.status_code +puts response.body +puts response.parsed_body +puts response.headers +``` + + +# Legacy Templates + +For this example, we assume you have created a [legacy template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). Following is the template content we used for testing. + +Template ID (replace with your own): + ```text 13b8f94f-bcae-4ec6-b752-70d6cb59f932 ``` @@ -57,7 +158,6 @@ personalization.add_to(Email.new(email: 'test@example.com')) personalization.add_substitution(Substitution.new(key: '-name-', value: 'Example User')) personalization.add_substitution(Substitution.new(key: '-city-', value: 'Denver')) mail.add_personalization(personalization) -mail.add_content(Content.new(type: 'text/html', value: 'I\'m replacing the body tag')) mail.template_id = '13b8f94f-bcae-4ec6-b752-70d6cb59f932' sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) @@ -68,6 +168,7 @@ rescue Exception => e end puts response.status_code puts response.body +puts response.parsed_body puts response.headers ``` @@ -95,12 +196,6 @@ data = JSON.parse('{ "from": { "email": "test@example.com" }, - "content": [ - { - "type": "text/html", - "value": "I\'m replacing the body tag" - } - ], "template_id": "13b8f94f-bcae-4ec6-b752-70d6cb59f932" }') sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) @@ -111,6 +206,7 @@ rescue Exception => e end puts response.status_code puts response.body +puts response.parsed_body puts response.headers ``` @@ -141,3 +237,51 @@ Find more information about all of SendGrid's whitelabeling related documentatio You can find documentation for how to view your email statistics via the UI [here](https://app.sendgrid.com/statistics) and via API [here](https://github.com/sendgrid/sendgrid-ruby/blob/master/USAGE.md#stats). Alternatively, we can post events to a URL of your choice via our [Event Webhook](https://sendgrid.com/docs/API_Reference/Webhooks/event.html) about events that occur as SendGrid processes your email. + +You can also use the email statistics helper to make it easier to interact with the API. + +```ruby +require 'sendgrid-ruby' +require 'date' + +include SendGrid + +sg_client = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']).client +stats = SendGrid::EmailStats.new(sendgrid_client: sg_client) + +# Fetch stats by day, between 2 dates +from = Date.new(2017, 10, 01) +to = Date.new(2017, 10, 12) + +email_stats = stats.by_day(from, to) + +email_stats.metrics + +if !email_stats.error? + email_stats.metrics.each do |metric| + puts "Date - #{metric.date}" + puts "Number of Requests - #{metric.requests}" + puts "Bounces - #{metric.bounces}" + puts "Opens - #{metric.opens}" + puts "Clicks - #{metric.clicks}" + end +end + +# Fetch stats by week, between 2 dates for a category +from = Date.new(2017, 10, 01) +to = Date.new(2017, 10, 12) +category = 'abcd' + +email_stats = stats.by_week(from, to, category) + +if !email_stats.error? + email_stats.metrics.each do |metric| + puts "Date - #{metric.date}" + puts "Number of Requests - #{metric.requests}" + puts "Bounces - #{metric.bounces}" + puts "Opens - #{metric.opens}" + puts "Clicks - #{metric.clicks}" + end +end + +``` diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 00000000..eb4c304f --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,12 @@ +FROM ruby:2.4.2-jessie + +# Clone sendgrid-ruby +WORKDIR /sources +RUN git clone https://github.com/sendgrid/sendgrid-ruby.git + +# Bundle +WORKDIR /sources/sendgrid-ruby +RUN bundle install + +# Install prism +RUN curl https://raw.githubusercontent.com/stoplightio/prism/master/install.sh | sh diff --git a/docker/README.md b/docker/README.md new file mode 100644 index 00000000..6db894cc --- /dev/null +++ b/docker/README.md @@ -0,0 +1,30 @@ +# Docker image for sendgrid-ruby + +## Quickstart +1. [Install Docker](https://docs.docker.com/engine/installation/) on your machine. +2. Run `docker run --rm -it sendgrid/sendgrid-ruby irb`. +3. Run `require './lib/sendgrid-ruby.rb'`. + +## Poke around + +If you would like to just poke around in the image and check some examples: +```sh +docker run --rm -it sendgrid/sendgrid-ruby bash +``` + +If you want to mount your fork or specific version of the gem: +```sh +docker run --rm -v /path/to/local/sendgrid-ruby:/sources/sendgrid-ruby -it sendgrid/sendgrid-ruby bash +``` + +## Running tests + +If you would like to run the tests present in the image: +```sh +docker run --rm sendgrid/sendgrid-ruby rake +``` + +If you want to run tests on your fork or a specific version, mount the codebase onto the image: +```sh +docker run --rm -v /path/to/local/sendgrid-ruby:/sources/sendgrid-ruby sendgrid/sendgrid-ruby rake +``` diff --git a/examples/helpers/mail/example.rb b/examples/helpers/mail/example.rb index d92f0066..bf69df2b 100644 --- a/examples/helpers/mail/example.rb +++ b/examples/helpers/mail/example.rb @@ -125,5 +125,23 @@ def kitchen_sink puts response.headers end +def dynamic_template_data_hello_world + mail = Mail.new + mail.template_id = '' # a non-legacy template id + mail.from = Email.new(email: 'test@example.com') + subject = 'Dynamic Template Data Hello World from the SendGrid Ruby Library' + mail.subject = subject + personalization = Personalization.new + personalization.add_to(Email.new(email: 'test1@example.com', name: 'Example User')) + personalization.add_dynamic_template_data({ + "variable" => [ + {"foo" => "bar"}, {"foo" => "baz"} + ] + }) + mail.add_personalization(personalization) +end + hello_world kitchen_sink +dynamic_template_data_hello_world + diff --git a/examples/ips/ips.rb b/examples/ips/ips.rb index 0d565668..c6d41eee 100644 --- a/examples/ips/ips.rb +++ b/examples/ips/ips.rb @@ -23,6 +23,19 @@ puts response.body puts response.headers +################################################## +# Retrieve unassigned IPs # +# GET /ips # + +params = {} +response = sg.client.ips.get(query_params: params) +all_ips = JSON.parse(response.body) +unassigned_ips = all_ips.select {|ip| ip.subusers.empty?} +puts response.status_code +puts response.body +puts unassigned_ips +puts response.headers + ################################################## # Create an IP pool. # # POST /ips/pools # diff --git a/lib/sendgrid-ruby.rb b/lib/sendgrid-ruby.rb index f856ab39..2ea10ca9 100644 --- a/lib/sendgrid-ruby.rb +++ b/lib/sendgrid-ruby.rb @@ -1,5 +1,6 @@ require_relative 'sendgrid/client' require_relative 'sendgrid/version' +require_relative 'sendgrid/helpers/ip_management/ip_management' require_relative 'sendgrid/helpers/mail/asm' require_relative 'sendgrid/helpers/mail/attachment' require_relative 'sendgrid/helpers/mail/bcc_settings' diff --git a/lib/sendgrid/helpers/inbound/README.md b/lib/sendgrid/helpers/inbound/README.md index c4f288a3..157ad4bb 100644 --- a/lib/sendgrid/helpers/inbound/README.md +++ b/lib/sendgrid/helpers/inbound/README.md @@ -30,7 +30,7 @@ bundle install ruby ./lib/sendgrid/helpers/inbound/send.rb ./lib/sendgrid/helpers/inbound/sample_data/default_data.txt ``` -More sample data can be found [here](https://github.com/sendgrid/sendgrid-ruby/tree/master/sendgrid/helpers/inbound/sample_data). +More sample data can be found [here](https://github.com/sendgrid/sendgrid-ruby/tree/master/lib/sendgrid/helpers/inbound/sample_data). View the results in the first terminal. diff --git a/lib/sendgrid/helpers/ip_management/ip_management.rb b/lib/sendgrid/helpers/ip_management/ip_management.rb new file mode 100644 index 00000000..d6007ffd --- /dev/null +++ b/lib/sendgrid/helpers/ip_management/ip_management.rb @@ -0,0 +1,17 @@ +require 'json' + +module SendGrid + class IpManagement + attr_accessor :sendgrid_client + + def initialize(sendgrid_client:) + @sendgrid_client = sendgrid_client + end + + def unassigned + response = @sendgrid_client.ips.get + ips = JSON.parse(response.body) + ips.select {|ip| ip.subusers.empty?} + end + end +end diff --git a/lib/sendgrid/helpers/mail/attachment.rb b/lib/sendgrid/helpers/mail/attachment.rb index 5fa2fb79..1876dbd3 100644 --- a/lib/sendgrid/helpers/mail/attachment.rb +++ b/lib/sendgrid/helpers/mail/attachment.rb @@ -1,4 +1,5 @@ require 'json' +require 'base64' module SendGrid class Attachment @@ -11,11 +12,18 @@ def initialize end def content=(content) + @encoded_content = nil @content = content end def content - @content + return @encoded_content if @encoded_content + + if @content.respond_to?(:read) + @encoded_content = encode @content + else + @encoded_content = @content + end end def type=(type) @@ -59,5 +67,20 @@ def to_json(*) 'content_id' => self.content_id }.delete_if { |_, value| value.to_s.strip == '' } end + + private + + def encode(io) + str = io.read + # Since the API expects UTF-8, we need to ensure that we're + # converting other formats to it so (byte-wise) Base64 encoding + # will come through properly on the other side. + # + # Not much to be done to try to handle encoding for files opened + # in binary mode, but at least we can faithfully convey the + # bytes. + str = str.encode('UTF-8') unless io.respond_to?(:binmode?) && io.binmode? + Base64.encode64 str + end end end diff --git a/lib/sendgrid/helpers/mail/custom_arg.rb b/lib/sendgrid/helpers/mail/custom_arg.rb index ed760e76..69b0558d 100644 --- a/lib/sendgrid/helpers/mail/custom_arg.rb +++ b/lib/sendgrid/helpers/mail/custom_arg.rb @@ -4,7 +4,7 @@ module SendGrid class CustomArg def initialize(key: nil, value: nil) @custom_arg = {} - (key.nil? || value.nil?) ? @custom_arg = nil : @custom_arg[key] = value + (key.nil? || value.nil?) ? @custom_arg = nil : @custom_arg[key.to_s] = value.to_s end def custom_arg=(custom_arg) diff --git a/lib/sendgrid/helpers/mail/mail.rb b/lib/sendgrid/helpers/mail/mail.rb index 37db5629..023b2833 100644 --- a/lib/sendgrid/helpers/mail/mail.rb +++ b/lib/sendgrid/helpers/mail/mail.rb @@ -60,6 +60,13 @@ def add_content(content) @contents << content.to_json end + def check_for_secrets(patterns) + contents = @contents.map { |content| content['value'] }.join(' ') + patterns.each do |pattern| + raise SecurityError.new('Content contains sensitive information.') if contents.match(pattern) + end + end + def add_attachment(attachment) @attachments << attachment.to_json end diff --git a/lib/sendgrid/helpers/mail/personalization.rb b/lib/sendgrid/helpers/mail/personalization.rb index 60ba319f..ad6d5c18 100644 --- a/lib/sendgrid/helpers/mail/personalization.rb +++ b/lib/sendgrid/helpers/mail/personalization.rb @@ -3,7 +3,8 @@ module SendGrid class Personalization - attr_reader :tos, :ccs, :bccs, :headers, :substitutions, :custom_args + attr_reader :tos, :ccs, :bccs, :headers, :substitutions, :custom_args, + :dynamic_template_data def initialize @tos = [] @@ -13,6 +14,7 @@ def initialize @headers = {} @substitutions = {} @custom_args = {} + @dynamic_template_data = {} @send_at = nil end @@ -51,6 +53,10 @@ def add_custom_arg(custom_arg) @custom_args = @custom_args.merge(custom_arg['custom_arg']) end + def add_dynamic_template_data(dynamic_template_data) + @dynamic_template_data.merge!(dynamic_template_data) + end + def send_at=(send_at) @send_at = send_at end @@ -68,6 +74,7 @@ def to_json(*) 'headers' => self.headers, 'substitutions' => self.substitutions, 'custom_args' => self.custom_args, + 'dynamic_template_data' => self.dynamic_template_data, 'send_at' => self.send_at }.delete_if { |_, value| value.to_s.strip == '' || value == [] || value == {}} end diff --git a/lib/sendgrid/version.rb b/lib/sendgrid/version.rb index 16ee5533..0d271849 100644 --- a/lib/sendgrid/version.rb +++ b/lib/sendgrid/version.rb @@ -1,3 +1,3 @@ module SendGrid - VERSION = '5.2.0' + VERSION = '5.3.0' end diff --git a/sendgrid-ruby.gemspec b/sendgrid-ruby.gemspec index 64fba290..844afb17 100644 --- a/sendgrid-ruby.gemspec +++ b/sendgrid-ruby.gemspec @@ -19,11 +19,12 @@ Gem::Specification.new do |spec| spec.executables = spec.files.grep(/^bin/) { |f| File.basename(f) } spec.test_files = spec.files.grep(/^(test|spec|features)/) spec.require_paths = ['lib'] - spec.add_dependency 'ruby_http_client', '~> 3.2' + spec.add_dependency 'ruby_http_client', '~> 3.3.0' spec.add_dependency 'sinatra', '>= 1.4.7', '< 3' spec.add_development_dependency 'rake', '~> 0' spec.add_development_dependency 'rspec' spec.add_development_dependency 'pry' spec.add_development_dependency 'faker' + spec.add_development_dependency 'rubocop' spec.add_development_dependency 'minitest', '~> 5.9' end diff --git a/spec/sendgrid/helpers/ip_management/ip_management_spec.rb b/spec/sendgrid/helpers/ip_management/ip_management_spec.rb new file mode 100644 index 00000000..e8f30eb2 --- /dev/null +++ b/spec/sendgrid/helpers/ip_management/ip_management_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe SendGrid::IpManagement do + let(:sendgrid_client) { SendGrid::API.new(api_key: 'fake_key').client } + let(:ip_management) { SendGrid::IpManagement.new(sendgrid_client: sendgrid_client) } + + describe '.new' do + it 'initializes correctly' do + expect(ip_management).to be_a SendGrid::IpManagement + end + end +end diff --git a/test/sendgrid/helpers/mail/test_attachment.rb b/test/sendgrid/helpers/mail/test_attachment.rb new file mode 100644 index 00000000..f66ebb16 --- /dev/null +++ b/test/sendgrid/helpers/mail/test_attachment.rb @@ -0,0 +1,35 @@ +# coding: utf-8 +require_relative "../../../../lib/sendgrid/helpers/mail/attachment" +include SendGrid +require "json" +require "minitest/autorun" + +class TestAttachment < Minitest::Test + SAMPLE_INPUT = """Es blüht so grün wie Blüten blüh'n im Frühling +Es blüht so grün wie Blüten blüh'n im Frühling +Es blüht so grün wie Blüten blüh'n im Frühling +Es blüht so grün wie Blüten blüh'n im Frühling +Es blüht so grün wie Blüten blüh'n im Frühling +""".force_encoding('UTF-8').encode + + def setup + end + + def test_io_enocding + attachment = Attachment.new + attachment.content = StringIO.new(SAMPLE_INPUT) + + expected = { + "content" => "RXMgYmzDvGh0IHNvIGdyw7xuIHdpZSBCbMO8dGVuIGJsw7xoJ24gaW0gRnLD\nvGhsaW5nCkVzIGJsw7xodCBzbyBncsO8biB3aWUgQmzDvHRlbiBibMO8aCdu\nIGltIEZyw7xobGluZwpFcyBibMO8aHQgc28gZ3LDvG4gd2llIEJsw7x0ZW4g\nYmzDvGgnbiBpbSBGcsO8aGxpbmcKRXMgYmzDvGh0IHNvIGdyw7xuIHdpZSBC\nbMO8dGVuIGJsw7xoJ24gaW0gRnLDvGhsaW5nCkVzIGJsw7xodCBzbyBncsO8\nbiB3aWUgQmzDvHRlbiBibMO8aCduIGltIEZyw7xobGluZwo=\n" + } + + json = attachment.to_json + + # Double check that the decoded json matches original input. + decoded = Base64.decode64(json["content"]).force_encoding('UTF-8').encode + + assert_equal(decoded, SAMPLE_INPUT) + + assert_equal(json, expected) + end +end diff --git a/test/sendgrid/helpers/mail/test_mail.rb b/test/sendgrid/helpers/mail/test_mail.rb index 87dc8581..e8e34b33 100644 --- a/test/sendgrid/helpers/mail/test_mail.rb +++ b/test/sendgrid/helpers/mail/test_mail.rb @@ -207,6 +207,21 @@ def test_add_custom_arg assert_equal mail.to_json, expected_json end + def test_add_non_string_custom_arg + mail = Mail.new + mail.add_custom_arg(CustomArg.new(key: "Integer", value: 1)) + mail.add_custom_arg(CustomArg.new(key: "Array", value: [1, "a", true])) + mail.add_custom_arg(CustomArg.new(key: "Hash", value: {"a" => 1, "b" => 2})) + expected_json = { + "custom_args"=>{ + "Integer"=>"1", + "Array"=>"[1, \"a\", true]", + "Hash"=>"{\"a\"=>1, \"b\"=>2}", + } + } + assert_equal mail.to_json, expected_json + end + def test_add_attachment mail = SendGrid::Mail.new mail.add_attachment('foo') @@ -235,4 +250,12 @@ def test_add_invalid_category mail.add_category('foo') end end + + def test_check_for_secrets + mail = Mail.new + mail.add_content(Content.new(type: 'text/plain', value: 'Sensitive information: SG.a123b456')) + assert_raises(SecurityError) do + mail.check_for_secrets([/SG.[a-zA-Z0-9_-]*/]) + end + end end diff --git a/test/sendgrid/helpers/mail/test_personalizations.rb b/test/sendgrid/helpers/mail/test_personalizations.rb index 383ed8b9..320f24b2 100644 --- a/test/sendgrid/helpers/mail/test_personalizations.rb +++ b/test/sendgrid/helpers/mail/test_personalizations.rb @@ -143,4 +143,19 @@ def test_add_custom_arg assert_equal @personalization.to_json, expected_json end + def test_add_dynamic_template_data + @personalization = Personalization.new() + @personalization.add_dynamic_template_data({ + "name"=>"Example User", + "city"=> "Denver" + }) + expected_json = { + "dynamic_template_data"=>{ + "name"=>"Example User", + "city"=>"Denver" + } + } + assert_equal @personalization.to_json, expected_json + end + end \ No newline at end of file diff --git a/test/sendgrid/test_sendgrid-ruby.rb b/test/sendgrid/test_sendgrid-ruby.rb index e9ccc7c7..e34295a1 100644 --- a/test/sendgrid/test_sendgrid-ruby.rb +++ b/test/sendgrid/test_sendgrid-ruby.rb @@ -55,7 +55,7 @@ def test_init ') assert_equal(test_headers, sg.request_headers) assert_equal("v3", sg.version) - assert_equal("5.2.0", SendGrid::VERSION) + assert_equal("5.3.0", SendGrid::VERSION) assert_instance_of(SendGrid::Client, sg.client) end @@ -2667,4 +2667,77 @@ def test_whitelabel_links__link_id__subuser_post self.assert_equal('200', response.status_code) end + + + def test_license_file_correct_year_range + if File.exist?('./LICENSE.txt') + # get only the first line from the license txt file + year_range = File.open('./LICENSE.txt', &:readline).gsub(/[^\d-]/, '') + self.assert_equal("2014-#{Time.now.year}", year_range) + end + end + + def test_docker_exists + assert(File.file?('./Dockerfile') || File.file?('./docker/Dockerfile')) + end + + # def test_docker_compose_exists + # assert(File.file?('./docker-compose.yml') || File.file?('./docker/docker-compose.yml')) + # end + + def test_env_sample_exists + assert(File.file?('./.env_sample')) + end + + def test_gitignore_exists + assert(File.file?('./.gitignore')) + end + + def test_travis_exists + assert(File.file?('./.travis.yml')) + end + + def test_codeclimate_exists + assert(File.file?('./.codeclimate.yml')) + end + + def test_changelog_exists + assert(File.file?('./CHANGELOG.md')) + end + + def test_code_of_conduct_exists + assert(File.file?('./CODE_OF_CONDUCT.md')) + end + + def test_contributing_exists + assert(File.file?('./CONTRIBUTING.md')) + end + + def test_issue_template_exists + assert(File.file?('./.github/ISSUE_TEMPLATE')) + end + + def test_license_exists + assert(File.file?('./LICENSE.txt')) + end + + def test_pull_request_template_exists + assert(File.file?('./.github/PULL_REQUEST_TEMPLATE')) + end + + def test_readme_exists + assert(File.file?('./README.md')) + end + + def test_troubleshooting_exists + assert(File.file?('./TROUBLESHOOTING.md')) + end + + def test_usage_exists + assert(File.file?('./USAGE.md')) + end + + def test_use_cases_exists + assert(File.file?('./USE_CASES.md')) + end end