Class: AeEasy::Core::Mock::FakeDb

Inherits:
Object
  • Object
show all
Defined in:
lib/ae_easy/core/mock/fake_db.rb

Overview

Fake in memory database that emulates `Answersengine` database objects' black box behavior.

Constant Summary collapse

PAGE_KEYS =

Page id keys, analog to primary keys.

['gid'].freeze
OUTPUT_KEYS =

Output id keys, analog to primary keys.

['_id', '_collection'].freeze
DEFAULT_COLLECTION =

Default collection for saved outputs

'default'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ FakeDb

Initialize fake database.

Parameters:

  • opts (Hash) (defaults to: {})

    ({}) Configuration options.

Options Hash (opts):

  • :job_id (Integer, nil)

    Job id default value.

  • :page_gid (String, nil)

    Page gid default value.

  • :allow_page_gid_override (Boolean, nil) — default: false

    Specify whenever page gid can be overrided on page insert.



106
107
108
109
110
# File 'lib/ae_easy/core/mock/fake_db.rb', line 106

def initialize opts = {}
  self.job_id = opts[:job_id]
  self.page_gid = opts[:page_gid]
  @allow_page_gid_override = opts[:allow_page_gid_override].nil? ? false : !!opts[:allow_page_gid_override]
end

Class Method Details

.build_fake_page(opts = {}) ⇒ Hash

Build a fake page by using FakeDb engine.

Parameters:

  • opts (Hash) (defaults to: {})

    ({}) Configuration options (see #initialize).

Options Hash (opts):

  • :url (String) — default: 'https://example.com'

    Page url.

Returns:

  • (Hash)


52
53
54
55
56
57
# File 'lib/ae_easy/core/mock/fake_db.rb', line 52

def self.build_fake_page opts = {}
  page = {
    'url' => (opts[:url] || 'https://example.com')
  }
  build_page page, opts
end

.build_page(page, opts = {}) ⇒ Hash

Build a page with defaults by using FakeDb engine.

Parameters:

  • page (Hash)

    Page initial values.

  • opts (Hash) (defaults to: {})

    ({}) Configuration options (see #initialize).

Returns:

  • (Hash)


39
40
41
42
43
44
# File 'lib/ae_easy/core/mock/fake_db.rb', line 39

def self.build_page page, opts = {}
  temp_db = AeEasy::Core::Mock::FakeDb.new opts
  temp_db.enable_page_gid_override
  temp_db.pages << page
  temp_db.pages.first
end

.fake_uuid(seed = nil) ⇒ String

Generate a fake UUID.

Parameters:

  • seed (nil) (defaults to: nil)

    Object to use as seed for uuid.

Returns:

  • (String)


28
29
30
31
# File 'lib/ae_easy/core/mock/fake_db.rb', line 28

def self.fake_uuid seed = nil
  seed ||= (Time.new.to_f + rand)
  Digest::SHA1.hexdigest seed.to_s
end

.new_collection(keys, opts = {}) ⇒ AeEasy::Core::SmartCollection

Generate a smart collection with keys and initial values.

Parameters:

  • keys (Array)

    Analog to primary keys, combination will be uniq.

  • opts (Hash) (defaults to: {})

    Configuration options (see AeEasy::Core::SmartCollection#initialize).

Returns:



19
20
21
# File 'lib/ae_easy/core/mock/fake_db.rb', line 19

def self.new_collection keys, opts = {}
  AeEasy::Core::SmartCollection.new keys, opts
end

Instance Method Details

#allow_page_gid_override?Boolean

Specify whenever page gid overriding by user is allowed on page

insert.

Returns:

  • (Boolean)

    `true` when allowed, else `false`.



95
96
97
# File 'lib/ae_easy/core/mock/fake_db.rb', line 95

def allow_page_gid_override?
  @allow_page_gid_override ||= false
end

#disable_page_gid_overrideObject

Disable page gid override on page insert.



87
88
89
# File 'lib/ae_easy/core/mock/fake_db.rb', line 87

def disable_page_gid_override
  @allow_page_gid_override = false
end

#enable_page_gid_overrideObject

Enable page gid override on page insert.



82
83
84
# File 'lib/ae_easy/core/mock/fake_db.rb', line 82

def enable_page_gid_override
  @allow_page_gid_override = true
end

#generate_output_id(data) ⇒ String

Generate a fake UUID based on output fields without `_` prefix.

Parameters:

  • data (Hash)

    Output data.

Returns:

  • (String)


187
188
189
190
# File 'lib/ae_easy/core/mock/fake_db.rb', line 187

def generate_output_id data
  seed = data.select{|k,v|k.to_s =~ /^[^_]/}.hash
  self.class.fake_uuid seed
end

#generate_page_gid(data) ⇒ String

Generate a fake UUID based on page data:

* url
* method
* headers
* fetch_type
* cookie
* no_redirect
* body
* ua_type

Parameters:

  • data (Hash)

    Output data.

Returns:

  • (String)


125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/ae_easy/core/mock/fake_db.rb', line 125

def generate_page_gid data
  fields = [
    'url',
    'method',
    'headers',
    'fetch_type',
    'cookie',
    'no_redirect',
    'body',
    'ua_type'
  ]
  seed = data.select{|k,v|fields.include? k}.hash
  self.class.fake_uuid seed
end

#job_idInteger?

Fake job id.

Returns:

  • (Integer, nil)


61
62
63
# File 'lib/ae_easy/core/mock/fake_db.rb', line 61

def job_id
  @job_id ||= rand(1000) + 1
end

#job_id=(value) ⇒ Object

Set fake job id value.



66
67
68
# File 'lib/ae_easy/core/mock/fake_db.rb', line 66

def job_id= value
  @job_id = value
end

#match?(data, filters) ⇒ Boolean

Note:

Missing and `nil` values on `data` will match when `filters`' field is `nil`.

Match data to filters.

Parameters:

  • data

    Hash containing data.

  • filters

    Filters to apply on match.

Returns:

  • (Boolean)


232
233
234
235
236
237
# File 'lib/ae_easy/core/mock/fake_db.rb', line 232

def match? data, filters
  filters.each do |key, value|
    return false if data[key] != value
  end
  true
end

#output_defaultsHash

Get output keys with key generators to emulate saving on db.

Returns:

  • (Hash)


196
197
198
199
200
201
202
203
# File 'lib/ae_easy/core/mock/fake_db.rb', line 196

def output_defaults
  @output_keys ||= {
    '_collection' => DEFAULT_COLLECTION,
    '_job_id' => lambda{|output| job_id},
    '_created_at' => lambda{|output| Time.new.strftime('%Y-%m-%dT%H:%M:%SZ')},
    '_gid' => lambda{|output| page_gid}
  }
end

#outputsAeEasy::Core::SmartCollection

Stored output collection



208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/ae_easy/core/mock/fake_db.rb', line 208

def outputs
  return @outputs unless @outputs.nil?
  collection = self.class.new_collection OUTPUT_KEYS,
    defaults: output_defaults
  collection.bind_event(:before_defaults) do |collection, raw_item|
    AeEasy::Core.deep_stringify_keys raw_item
  end
  collection.bind_event(:before_insert) do |collection, item, match|
    item['_id'] ||= generate_output_id item
    item
  end
  @outputs ||= collection
end

#page_defaultsHash

Get page keys with key generators to emulate saving on db.

Returns:

  • (Hash)


144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/ae_easy/core/mock/fake_db.rb', line 144

def page_defaults
  @page_keys ||= {
    'url' => nil,
    'method' => 'GET',
    'headers' => {},
    'fetch_type' => 'standard',
    'cookie' => nil,
    'no_redirect' => false,
    'body' => nil,
    'ua_type' => 'desktop',
    'vars' => {}
  }
end

#page_gidInteger?

Current fake page gid.

Returns:

  • (Integer, nil)


72
73
74
# File 'lib/ae_easy/core/mock/fake_db.rb', line 72

def page_gid
  @page_gid ||= self.class.fake_uuid
end

#page_gid=(value) ⇒ Object

Set current fake page gid value.



77
78
79
# File 'lib/ae_easy/core/mock/fake_db.rb', line 77

def page_gid= value
  @page_gid = value
end

#pagesAeEasy::Core::SmartCollection

Note:

Page gid will be replaced on insert by an auto generated uuid unless page gid overriding is enabled (see #allow_page_gid_override?)

Stored page collection.



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/ae_easy/core/mock/fake_db.rb', line 165

def pages
  return @pages unless @page.nil?

  collection = self.class.new_collection PAGE_KEYS,
    defaults: page_defaults
  collection.bind_event(:before_defaults) do |collection, raw_item|
    AeEasy::Core.deep_stringify_keys raw_item
  end
  collection.bind_event(:before_insert) do |collection, item, match|
    if item['gid'].nil? || !allow_page_gid_override?
      item['gid'] = generate_page_gid item
    end
    item
  end
  @pages ||= collection
end

#query(collection, filter, offset = 0, limit = nil) ⇒ Object

Note:

Warning: It uses table scan to filter and should be used on test suites only.

Search items from a collection.

Parameters:

  • collection (Symbol)

    Allowed values: `:outputs`, `:pages`.

  • filter (Hash)

    Filters to query.

  • offset (Integer) (defaults to: 0)

    (0) Search results offset.

  • limit (Integer|nil) (defaults to: nil)

    (nil) Limit search results count. Set to `nil` for unlimited.

Raises:

  • ArgumentError On unknown collection.



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
# File 'lib/ae_easy/core/mock/fake_db.rb', line 249

def query collection, filter, offset = 0, limit = nil
  return [] unless limit.nil? || limit > 0

  # Get collection items
  items = case collection
  when :outputs
    outputs
  when :pages
    pages
  else
    raise ArgumentError.new "Unknown collection #{collection}."
  end

  # Search items
  count = 0
  matches = []
  items.each do |item|
    next unless match? item, filter
    count += 1

    # Skip until offset
    next unless offset < count
    # Break on limit reach
    break unless limit.nil? || matches.count < limit
    matches << item
  end
  matches
end