Class: NContent::SDK::Testing::ServerMock

Inherits:
Sinatra::Base
  • Object
show all
Defined in:
lib/ncontent/sdk/testing/server_mock.rb

Overview

Clase que simula el servicio de nContent: Ver robots.thoughtbot.com/how-to-stub-external-services-in-tests

Defined Under Namespace

Classes: ValidationError

Constant Summary collapse

COLLECTION_NAMES =
%w(
  categories content_versions contents download_authorizations
  media_processes media_profiles media_resources
).freeze
RESOURCE_TYPES =
COLLECTION_NAMES.map(&:singularize).freeze

Class Method Summary collapse

Class Method Details

.clear_collections!Object



45
46
47
# File 'lib/ncontent/sdk/testing/server_mock.rb', line 45

def self.clear_collections!
  @collections = nil
end

.collectionsObject



49
50
51
# File 'lib/ncontent/sdk/testing/server_mock.rb', line 49

def self.collections
  @collections ||= get_blank_collection_set
end

.get_blank_collection_setObject



38
39
40
41
42
43
# File 'lib/ncontent/sdk/testing/server_mock.rb', line 38

def self.get_blank_collection_set
  COLLECTION_NAMES.inject({}) do |hash, collection_name|
    hash[collection_name] = {}
    hash
  end.with_indifferent_access
end

.get_resource(resource_type, resource_id) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/ncontent/sdk/testing/server_mock.rb', line 156

def self.get_resource(resource_type, resource_id)
  collection_name = resource_type.pluralize
  requested_resource = self.collections[collection_name.to_s].fetch resource_id, nil

  # Traerse los MR's:
  requested_resource[:media_resources] = self.media_resources.values.select do |mr|
    mr[:parent_document_type] == "Content" && mr[:parent_document_id] == resource_id
  end.map do |mr|
    mr[:media_resources] = self.media_resources.values.select do |c_mr|
      c_mr[:parent_document_type] == "MediaResource" && c_mr[:parent_document_id] == mr[:id]
    end
    mr
  end if requested_resource.present? && collection_name == 'contents'

  requested_resource
end

.get_resource_headers(collection_name, resource_id) ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/ncontent/sdk/testing/server_mock.rb', line 173

def self.get_resource_headers(collection_name, resource_id)
  raise "no collection name given" unless collection_name.present?
  raise "no resource id given" unless resource_id.present?

  headers = {}
  headers = {
    "X-Frame-Options"         => "SAMEORIGIN",
    "X-Xss-Protection"        => "1; mode=block",
    "X-Content-Type-Options"  => "nosniff",
    "Location"                => "http://ecm.naranya.net:5000/#{collection_name}/#{resource_id}",
    "Content-Type"            => "application/json; charset=utf-8",
    "Vary"                    => "Accept-Encoding",
    "Etag"                    => '"a547f3ead872de01928f79724390aba4"',
    "Cache-Control"           => "max-age=0, private, must-revalidate",
    "Set-Cookie"              => "request_method=POST; path=/",
    "X-Request-Id"            => "a6463225-df54-450d-b571-7068f3c96364",
    "X-Runtime"               => "'0.241093'",
    "Transfer-Encoding"       => "chunked"
  } if self.collections[collection_name].key? resource_id
end

.method_missing(method_name, *args, &block) ⇒ Object



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
# File 'lib/ncontent/sdk/testing/server_mock.rb', line 53

def self.method_missing(method_name, *args, &block)
  if COLLECTION_NAMES.include? method_name.to_s

    # Create the method:
    define_singleton_method method_name do
      collections[method_name.to_s]
    end

    # Call the newly defined method:
    self.send method_name, *args
  elsif method_name =~ /\Aget_(\w+)\z/ && RESOURCE_TYPES.include?($1)

    # Create the method:
    define_singleton_method method_name do |resource_id|
      get_resource $1, resource_id
    end

    # Call the newly defined method:
    self.send method_name, *args
  elsif method_name =~ /\A(create|update|upsert)_(\w+)\z/ && RESOURCE_TYPES.include?($2)

    # Create the methods:
    %w(create update upsert).each do |method_prefix|
      new_method_name = "#{method_prefix}_#{$2}".to_sym
      define_singleton_method new_method_name do |*args|
        upsert_resource $2.pluralize, *args
      end
    end

    # Call the newly defined method:
    self.send method_name, *args
  else
    super # You *must* call super if you don't handle the
          # method, otherwise you'll mess up Ruby's method
          # lookup.
  end
end

.upsert_resource(collection_name, given_resource_attributes, resource_id = nil) ⇒ Object

Raises:



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
# File 'lib/ncontent/sdk/testing/server_mock.rb', line 91

def self.upsert_resource(collection_name, given_resource_attributes, resource_id = nil)
  # Ignore the ID:
  given_resource_attributes.delete 'id'

  invalid_attributes = given_resource_attributes.select do |k, v|
    v =~ /invalid/i
  end

  raise ValidationError, invalid_attributes.collect {} do |h, kv|
    k, v = kv;
    h[k] = ['is invalid']
    h
  end if invalid_attributes.any?

  if resource_id.present? && collections[collection_name].key?(resource_id)
    collections[collection_name][resource_id].merge! given_resource_attributes
  else
    # Caso especial:
    if collection_name == 'contents'
      given_resource_attributes.reverse_merge "lifecycle_state" => 'draft'

      # Generar iconos y screenshots en caso de que sea Game:
      if given_resource_attributes['type'] == "Game"
        icon = self.upsert_media_resource(
          roles: ["icon"],
          downloadable_url: "http://test-bucket.s3.amazonaws.com/icons/original/#{resource_id}.jpg",
          type: "image/jpg",
          access_type: "public",
          parent_document_id: resource_id,
          parent_document_type: "Content"
        )

        %w(120w 150w 300w).each do |processed_role|
          self.upsert_media_resource(
            roles: ["icon", "processed", "v2", processed_role],
            downloadable_url: "http://test-bucket.s3.amazonaws.com/icons/#{processed_role}/#{resource_id}.jpg",
            type: "image/jpg",
            access_type: "public",
            parent_document_id: icon[:id],
            parent_document_type: "MediaResource"
          )
        end

      end
    end

    resource_id = (BSON::ObjectId.new).to_s
    collections[collection_name][resource_id] = { id: resource_id }.merge(
      given_resource_attributes
    ).with_indifferent_access
  end

  collections[collection_name][resource_id]
end

.url_matcherObject

Éste método es útil para llamar “stub_request”, usando el host+port configurado por ENV



147
148
149
150
151
152
153
154
# File 'lib/ncontent/sdk/testing/server_mock.rb', line 147

def self.url_matcher
  @url_matcher ||= begin
    site_url = URI config.api_host
    pattern_string = site_url.host
    pattern_string += ":#{site_url.port}" unless site_url.port == 80
    Regexp.new pattern_string, "i"
  end
end