aboutsummaryrefslogtreecommitdiffstats
path: root/activestorage/test/service/shared_service_tests.rb
blob: ade91ab89a8c90ba28b9ac52fdc90bfb298922d7 (plain) (blame)
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
# frozen_string_literal: true

require "test_helper"
require "active_support/core_ext/securerandom"

module ActiveStorage::Service::SharedServiceTests
  extend ActiveSupport::Concern

  FIXTURE_KEY  = SecureRandom.base58(24)
  FIXTURE_DATA = "\211PNG\r\n\032\n\000\000\000\rIHDR\000\000\000\020\000\000\000\020\001\003\000\000\000%=m\"\000\000\000\006PLTE\000\000\000\377\377\377\245\331\237\335\000\000\0003IDATx\234c\370\377\237\341\377_\206\377\237\031\016\2603\334?\314p\1772\303\315\315\f7\215\031\356\024\203\320\275\317\f\367\201R\314\f\017\300\350\377\177\000Q\206\027(\316]\233P\000\000\000\000IEND\256B`\202".dup.force_encoding(Encoding::BINARY)

  included do
    setup do
      @service = self.class.const_get(:SERVICE)
      @service.upload FIXTURE_KEY, StringIO.new(FIXTURE_DATA)
    end

    teardown do
      @service.delete FIXTURE_KEY
    end

    test "uploading with integrity" do
      begin
        key  = SecureRandom.base58(24)
        data = "Something else entirely!"
        @service.upload(key, StringIO.new(data), checksum: Digest::MD5.base64digest(data))

        assert_equal data, @service.download(key)
      ensure
        @service.delete key
      end
    end

    test "uploading without integrity" do
      begin
        key  = SecureRandom.base58(24)
        data = "Something else entirely!"

        assert_raises(ActiveStorage::IntegrityError) do
          @service.upload(key, StringIO.new(data), checksum: Digest::MD5.base64digest("bad data"))
        end

        assert_not @service.exist?(key)
      ensure
        @service.delete key
      end
    end

    test "downloading" do
      assert_equal FIXTURE_DATA, @service.download(FIXTURE_KEY)
    end

    test "downloading in chunks" do
      chunks = []

      @service.download(FIXTURE_KEY) do |chunk|
        chunks << chunk
      end

      assert_equal [ FIXTURE_DATA ], chunks
    end

    test "existing" do
      assert @service.exist?(FIXTURE_KEY)
      assert_not @service.exist?(FIXTURE_KEY + "nonsense")
    end

    test "deleting" do
      @service.delete FIXTURE_KEY
      assert_not @service.exist?(FIXTURE_KEY)
    end

    test "deleting nonexistent key" do
      assert_nothing_raised do
        @service.delete SecureRandom.base58(24)
      end
    end
  end
end