File: messagebus_spec.rb

package info (click to toggle)
ruby-messagebus-api 3.0.7%2Bgit.20130130.97b34ece.REALLY.1.0.3-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 224 kB
  • sloc: ruby: 630; makefile: 4
file content (334 lines) | stat: -rw-r--r-- 11,788 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# Copyright 2012 Mail Bypass, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

dir = File.dirname(__FILE__)
require "#{dir}/../spec_helper"

class MessagebusTest < MessagebusApi::Messagebus
  attr_accessor :last_init_time
end

describe MessagebusApi::Messagebus do
  attr_reader :client, :api_key, :required_params

  def default_message_params
    {:toEmail => 'apitest1@messagebus.com',
     :toName => 'EmailUser',
     :fromEmail => 'api@messagebus.com',
     :fromName => 'API',
     :subject => 'Unit Test Message',
     :customHeaders => ["sender"=>"apitest1@messagebus.com"],
     :plaintextBody => 'This message is only a test sent by the Ruby Message Bus client library.',
     :htmlBody => "<html><body>This message is only a test sent by the Ruby Message Bus client library.</body></html>",
     :tags => ['RUBY', 'Unit Test Ruby']
    }
  end

  def default_template_message_params
    {:toEmail => 'apitest1@messagebus.com',
     :toName => 'John Smith',
     :templateKey => '66f6181bcb4cff4cd38fbc804a036db6',
     :customHeaders => ["reply-to"=>"apitest1@messagebus.com"],
     :mergeFields => ["%NAME%" => "John"]
    }
  end

  def create_success_result(num_result)
    list=[]
    num_result.times do
      list << @success_message
    end

    success_result = {
      "statusMessage" => "OK",
      "successCount" => num_result,
      "failureCount" => 0,
      "results" => list
    }
    success_result
  end

  def create_results_array
    results = {
      "statusMessage" => "OK",
      "results" => []
    }
    results
  end

  def json_parse(data)
    JSON.parse(data, :symbolize_names => true)
  end

  before do
    FakeWeb.allow_net_connect = false

    @api_key = "7215ee9c7d9dc229d2921a40e899ec5f"
    @client = MessagebusTest.new(@api_key)
    @success_message={
      "status" => 200,
      "messageId" => "abcdefghijklmnopqrstuvwxyz012345"
    }
    @simple_success_result = create_success_result(1)
  end

  describe "messagebus object set up correctly" do
    it "has correct headers set for api calls" do
      client = MessagebusApi::Messagebus.new(@api_key)
    end
  end

  describe "add cacert file to http communitcations" do
    it "raises error if cert file does not exist" do
      client = MessagebusApi::Messagebus.new(@api_key)
      cert_file_path = File.join(File.dirname(__FILE__), "nofile.pem")
      expect do
        client.cacert_info(cert_file_path)
      end.to raise_error
    end

    it "accepts a cert file that exists" do
      client = MessagebusApi::Messagebus.new(@api_key)
      cert_file_path = File.join(File.dirname(__FILE__), "cacert.pem")
      expect do
        client.cacert_info(cert_file_path)
      end.not_to raise_error
    end
  end

  describe "#add_message" do
    it "buffered send that adds to empty buffer" do
      client.add_message(default_message_params)
      expect(client.flushed?).to be_falsey
    end

    it "buffered send that adds to empty buffer and sends with flush_buffer flag" do
      FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => json_valid_send)
      client.add_message(default_message_params, true)
      expect(client.flushed?).to be_truthy
    end

    it "should have user-agent and x-messagebus-key set in request headers" do
      FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => json_valid_send)
      client.add_message(default_message_params, true)
      expect(client.flushed?).to be_truthy

      expect(FakeWeb.last_request.get_fields("X-MessageBus-Key")).not_to be_nil
      expect(FakeWeb.last_request.get_fields("User-Agent")).not_to be_nil
      expect(FakeWeb.last_request.get_fields("Content-Type")).not_to be_nil
    end

    it "buffered send that adds to a buffer and auto-flushes" do
      FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => create_success_result(client.message_buffer_size).to_json)
      (client.message_buffer_size-1).times do |idx|
        client.add_message(default_message_params)
        expect(client.flushed?).to be_falsey
      end
      client.add_message(default_message_params)
      expect(client.flushed?).to be_truthy
      expect(client.results[:results].size).to eq(client.message_buffer_size)
    end

    it "buffered send that adds templates to a buffer and auto-flushes" do
      FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/templates/send", :body => create_success_result(client.message_buffer_size).to_json)
      (client.message_buffer_size-1).times do |idx|
        client.add_message(default_template_message_params)
        expect(client.flushed?).to be_falsey
      end
      client.add_message(default_template_message_params)
      expect(client.flushed?).to be_truthy
      expect(client.results[:results].size).to eq(client.message_buffer_size)
    end
  end

  describe "#flush" do
    it "flush called on empty buffer" do
      client.flush
      expect(client.flushed?).to be_falsey
    end

    it "flush called on partially filled buffer" do
      message_count = 9
      FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => create_success_result(message_count).to_json)
      (message_count).times do |idx|
        client.add_message(default_message_params)
        expect(client.flushed?).to be_falsey
      end
      client.flush
      expect(client.flushed?).to be_truthy
      expect(client.results[:results].size).to eq(message_count)
    end

    it "doesnt reset connection if under a minute old" do
      current_init_time=client.last_init_time
      expect(current_init_time).to be > Time.now.utc-5
      FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => create_success_result(1).to_json)
      client.add_message(default_message_params)
      client.flush
      expect(client.flushed?).to be_truthy
      expect(client.results[:results].size).to eq(1)
      expect(client.last_init_time).to eq(current_init_time)
    end

    it "resets connection if over a minute old" do
      client.last_init_time=Time.now.utc-60
      current_init_time=client.last_init_time
      expect(current_init_time).to be < Time.now.utc-59
      FakeWeb.register_uri(:post, "https://api.messagebus.com/api/v3/emails/send", :body => create_success_result(1).to_json)
      client.add_message(default_message_params)
      client.flush
      expect(client.flushed?).to be_truthy
      expect(client.results[:results].size).to eq(1)
      expect(client.last_init_time).to be > current_init_time
    end
  end

  describe "#message_buffer_size=" do
    it "can set the buffer size" do
      client.message_buffer_size=(10)
      expect(client.message_buffer_size).to eq(10)
    end

    it "cannot set an invalid buffer size" do
      default_buffer_size = 20
      client.message_buffer_size=(-1)
      expect(client.message_buffer_size).to eq(default_buffer_size)

      client.message_buffer_size=(0)
      expect(client.message_buffer_size).to eq(default_buffer_size)

      client.message_buffer_size=(101)
      expect(client.message_buffer_size).to eq(default_buffer_size)

      client.message_buffer_size=(1)
      expect(client.message_buffer_size).to eq(1)

      client.message_buffer_size=(100)
      expect(client.message_buffer_size).to eq(100)
    end
  end

  describe "#delivery_errors" do
    it "request delivery errors list" do

      start_date_str="2011-01-01"
      end_date_str="2011-01-02"

      FakeWeb.register_uri(:get, "https://api.messagebus.com/api/v3/delivery_errors?startDate=#{start_date_str}&endDate=#{end_date_str}&tag=", :body => json_delivery_errors)
      expect do
        response = client.delivery_errors(start_date_str, end_date_str)
        expect(FakeWeb.last_request.body).to be_nil
        expect(response).to eq(json_parse(json_delivery_errors))
      end.not_to raise_error
    end
  end

  describe "#unsubscribes" do
    it "request blocked emails list" do

      start_date_str="2011-01-01T04:30:00+00:00"
      end_date_str="2011-01-02T04:30:00+00:00"

      expected_request="https://api.messagebus.com/api/v3/unsubscribes?startDate=#{URI::DEFAULT_PARSER.escape(start_date_str)}&endDate=#{URI::DEFAULT_PARSER.escape(end_date_str)}"

      FakeWeb.register_uri(:get, expected_request, :body => json_unsubscribes)
      expect do
        response = client.unsubscribes(start_date_str, end_date_str)
        expect(FakeWeb.last_request.body).to be_nil
        expect(response).to eq(json_parse(json_unsubscribes))
      end.not_to raise_error
    end
  end

  describe "#delete_mailing_list_entry" do
    it "remove from mailing list" do
      mailing_list_key="test_key"
      to_email="test@example.com"

      expected_request="https://api.messagebus.com/api/v3/mailing_list/test_key/entry/test@example.com"

      FakeWeb.register_uri(:delete, expected_request, :body => json_response_200)
      expect do
        response = client.delete_mailing_list_entry(mailing_list_key, to_email)
        expect(FakeWeb.last_request.body).to be_nil
        expect(response[:statusCode]).to eq(200)
      end.not_to raise_error

    end
  end

  describe "#add_mailing_list_entry" do
    it "add to mailing list" do
      mailing_list_key="test_key"
      merge_fields={"%EMAIL%"=>"test@example.com", "%PARAM1%"=>"test value"}
      expected_request="https://api.messagebus.com/api/v3/mailing_list/test_key/entries"

      FakeWeb.register_uri(:post, expected_request, :body => json_response_200)
      expect do
        response = client.add_mailing_list_entry(mailing_list_key, merge_fields)
        expect(FakeWeb.last_request.body).to match(/mergeField/)
        expect(response[:statusCode]).to eq(200)
      end.not_to raise_error

    end
  end

  describe "#mailing_lists" do
    it "get mailing lists" do
      expected_request="https://api.messagebus.com/api/v3/mailing_lists"

      FakeWeb.register_uri(:get, expected_request, :body => json_mailing_lists)
      expect do
        response = client.mailing_lists
        expect(response).to eq(json_parse(json_mailing_lists))
      end.not_to raise_error
    end
  end

  describe "#create_mailing_lists" do
    it "create a new mailing list" do
      expected_request="https://api.messagebus.com/api/v3/mailing_lists"

      FakeWeb.register_uri(:post, expected_request, :body => json_mailing_list_create)
      expect do
        response = client.create_mailing_lists("Test List", ["%EMAIL%", "%SOME_TOKEN%"])
        expect(response).to eq(json_parse(json_mailing_list_create))
      end.not_to raise_error
    end
  end

  describe "#stats" do
    it "stats" do
      start_date_str="2011-01-01"
      end_date_str="2011-01-02"

      expected_request="https://api.messagebus.com/api/v3/stats?startDate=#{start_date_str}&endDate=#{end_date_str}&tag="

      FakeWeb.register_uri(:get, expected_request, :body => json_stats)
      expect do
        response = client.stats(start_date_str, end_date_str)
        expect(response).to eq(json_parse(json_stats))
      end.not_to raise_error
    end
  end

  describe "#format_iso_time" do
    it "formats ISO time in format YYYY-MM-DDTHH:mm:ssZ" do
      expect(client.format_iso_time(Time.now)).to match(/2\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ/)
    end
  end


end