public
Fork of halorgium/mephisto
Description: A mirror of the mephisto code-base
Homepage: http://mephistoblog.com/
Clone URL: git://github.com/technoweenie/mephisto.git
Click here to lend your support to: mephisto and make a donation at www.pledgie.com !
technoweenie (author)
Thu May 15 17:48:51 -0700 2008
commit  478896185b0feb41ac328742f3527531c35f2cad
tree    4b4360f46dc7d1e5a0409bbb3e2ad8aea7b1ca28
parent  aa50252c19b28969e3bc217e70bed6a2f16d3a78 parent  33a730791242bb12b2bcd8cfab0a59e2b750b725
mephisto / test / test_helper.rb
100644 402 lines (340 sloc) 10.584 kb
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
ENV["RAILS_ENV"] = "test"
ENV['TZ'] = 'US/Central'
 
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
require 'test/spec'
require File.expand_path(File.dirname(__FILE__) + "/actor")
ASSET_PATH = File.join(RAILS_ROOT, 'test/fixtures/tmp/assets') unless Object.const_defined?(:ASSET_PATH)
require File.join(File.dirname(__FILE__), 'referenced_caching_test_helper')
 
Site.cache_sweeper_tracing = true
ActiveRecord::Base.instantiate_observers
 
Time.class_eval do
  class << self
    alias_method :real_now, :now
  end
 
  def self.mock_now
    @current_time
  end
 
  def self.mock!(time)
    class << Time ; alias_method :now, :mock_now; end
    @current_time = time
    yield
    class << Time ; alias_method :now, :real_now; end
  end
end
 
# TRUNCATE table to reset the id autonumber
# needed for the asset tests
# may have to rethink this...
Fixtures.class_eval do
  case ActiveRecord::Base.connection.class.name
    when /Mysql/
      def delete_existing_fixtures
        self.class.delete_existing_fixtures_for @connection, @table_name
      end
      
      def self.delete_existing_fixtures_for(connection, table_name)
        connection.delete "TRUNCATE TABLE #{table_name}", 'Fixture Delete'
        connection.execute "ALTER TABLE #{table_name} AUTO_INCREMENT = 1", 'Renumber Auto Increment'
      end
    when /PostgreSQL/
      def delete_existing_fixtures
        self.class.delete_existing_fixtures_for @connection, @table_name
      end
      
      def self.delete_existing_fixtures_for(connection, table_name)
        connection.delete "TRUNCATE TABLE #{table_name}", 'Fixture Delete'
        connection.execute "SELECT setval('public.#{table_name}_id_seq', 1, false)", 'Renumber Auto Increment'
      end
    else # tests will fail because they cant find Asset.find(1) then
      def self.delete_existing_fixtures_for(connection, table_name)
        connection.delete "DELETE FROM #{table_name}", 'Fixture Delete'
      end
  end
end
 
THEME_ROOT = RAILS_PATH + 'tmp/themes' unless Object.const_defined?(:THEME_ROOT)
THEME_FILES = [
  'about.yml',
  'preview.png',
  'images',
  'javascripts/behavior.js',
  'layouts/layout.liquid',
  'stylesheets/style.css',
  'templates/archive.liquid',
  'templates/author.liquid',
  'templates/error.liquid',
  'templates/home.liquid',
  'templates/index.liquid',
  'templates/page.liquid',
  'templates/search.liquid',
  'templates/section.liquid',
  'templates/single.liquid'
] unless Object.const_defined?(:THEME_FILES)
 
Mephisto::Routing.redirections.clear
Mephisto::Routing.deny 'limited_deny'
Mephisto::Routing.deny 'deny/foo/*'
Mephisto::Routing.deny 'deny/bar/?/?'
Mephisto::Routing.redirect \
  'redirect/from/*' => 'to/here',
  'redirect/match/wildcard/*' => 'this/$1',
  'redirect/match/vars/?/?' => 'this/$2/$1',
  '/sanitize/path' => 'foo://bar',
  'redirect/external' => 'http://external/$1/$2'
 
class Test::Unit::TestCase
  self.use_transactional_fixtures = true
  self.use_instantiated_fixtures = false
 
  def self.has_image_processor?
    @has_image_processor ||= Object.const_defined?(:ImageScience) || Object.const_defined?(:Magick)
  end
  
  def has_image_processor?
    self.class.has_image_processor?
  end
 
  def use_temp_file(path)
    temp_path = File.join(ASSET_PATH, File.basename(path))
    FileUtils.cp path, temp_path
    yield temp_path
  end
 
  def assert_template_result(expected, template, assigns={}, message=nil)
    assert_equal expected, Liquid::Template.parse(template).render(assigns)
  end
 
  def host!(hostname)
    @request.host = hostname
  end
 
  def liquid(key = nil)
    assigns = @controller.instance_variable_get(:@liquid_assigns)
    key ? assigns[key.to_s] : assigns
  end
 
  def assert_event_created(mode)
    assert_difference Event, :count do
      event = yield
      assert_equal mode, event.mode
    end
  end
 
  def assert_event_created_for(article, mode)
    article = contents(article)
    assert_event_created mode do
      yield article
      article.events.first
    end
  end
 
  def assert_no_event_created
    assert_no_difference(Event, :count) { yield }
  end
 
  def assert_attachment_created(num = 1)
    assert_difference Attachment, :count, num do
      yield
    end
  end
 
  def assert_no_attachment_created
    assert_attachment_created 0 do
      yield
    end
  end
 
  def assert_file_exists(file, message = nil)
    message ||= "File not found: #{file}"
    assert File.file?(file), message
  end
 
  def get_xpath(xpath)
    if @rexml.nil?
      @rexml = REXML::Document.new(@response.body)
      assert @rexml
    end
 
    REXML::XPath.match(@rexml, xpath)
  end
 
  def assert_xpath(xpath, msg=nil)
    assert !(get_xpath(xpath).empty?), "XPath '#{xpath}' was not matched: #{msg}"
  end
 
  def assert_not_xpath(xpath, msg=nil)
    assert get_xpath(xpath).empty?, "XPath '#{xpath}' was matched: #{msg}"
  end
 
  def assert_atom_entries_size(entries)
    assert_equal 1, get_xpath(%{/feed[count(child::entry)=#{entries}]}).size, "Atom 1.0 feed has wrong number of feed/entry nodes"
  end
 
  # Sets the current user in the session from the user fixtures.
  def login_as(user, site = nil)
    user = user ? users(user) : nil
    site = sites(site || :first)
    host! site.host
    @request.session[:user] = user ? User.authenticate_for(site, user.login, 'test') : nil
    if block_given?
      yield
      reset!
    end
  end
 
  def content_type(type)
    @request.env['Content-Type'] = type
  end
 
  def accept(accept)
    @request.env["HTTP_ACCEPT"] = accept
  end
 
  def authorize_as(user)
    if user
      @request.env["HTTP_AUTHORIZATION"] = "Basic #{Base64.encode64("#{users(user).login}:test")}"
      accept 'application/xml'
      content_type 'application/xml'
    else
      @request.env["HTTP_AUTHORIZATION"] = nil
      accept nil
      content_type nil
    end
    if block_given?
      yield
      reset!
    end
  end
 
  def assert_difference(object, method = nil, difference = 1)
    initial_value = object.send(method)
    yield
    assert_equal initial_value + difference, object.send(method), "#{object}##{method}"
  end
 
  def assert_no_difference(object, method, &block)
    assert_difference object, method, 0, &block
  end
 
  def login_with_cookie_as(user)
    @request.cookies['user'] = user ? CGI::Cookie.new(
      'name' => 'user',
      'value' => users(user).activation_code,
      'expires' => 2.weeks.from_now,
      'path' => '/',
      'domain' => 'test.host'
    ) : nil
  end
  
  # mocks a Liquid::Context
  def mock_context(assigns = {}, registers = {})
    returning Liquid::Context.new(assigns, registers) do |context|
      assigns.keys.each { |k| context[k].context = context }
    end
  end
 
  def liquify(*records, &block)
    BaseDrop.liquify(@context, *records, &block)
  end
 
  # Assert the block redirects to the login
  #
  # assert_requires_login(:bob) { |c| c.get :edit, :id => 1 }
  #
  def assert_requires_login(login = nil)
    yield HttpLoginProxy.new(self, login)
  end
 
  def assert_http_authentication_required(login = nil)
    yield XmlLoginProxy.new(self, login)
  end
 
  def reset!(*instance_vars)
    instance_vars = [:controller, :request, :response] unless instance_vars.any?
    instance_vars.collect! { |v| "@#{v}".to_sym }
    instance_vars.each do |var|
      instance_variable_set(var, instance_variable_get(var).class.new)
    end
  end
 
  def prepare_theme_fixtures
    FileUtils.rm_rf THEME_ROOT
    FileUtils.mkdir_p THEME_ROOT
    %w(1 2).each do |i|
      FileUtils.cp_r File.join(RAILS_ROOT, 'test/fixtures/themes/site-' + i), File.join(THEME_ROOT, 'site-' + i)
    end
  end
 
  def assert_models_equal(expected_models, actual_models, message = nil)
    to_test_param = lambda { |r| "<#{r.class}:#{r.to_param}>" }
    full_message = build_message(message, "<?> expected but was\n<?>.\n",
      expected_models.collect(&to_test_param), actual_models.collect(&to_test_param))
    assert_block(full_message) { expected_models == actual_models }
  end
end
 
class ActionController::IntegrationTest
  include Mephisto::Caching::ReferencedCachingTestHelper
  
  # creates a session as a logged on user
  def login_as(login)
    visit do |sess|
      sess.login_as login
      yield sess if block_given?
    end
  end
 
  # creates an anonymous session
  def visit
    open_session do |sess|
      sess.host = 'test.host'
      sess.extend Mephisto::Integration::Actor
      yield sess if block_given?
    end
  end
 
  def section_url_for(section, article = nil)
    (article ? sections(section).to_page_url(contents(article)) : sections(section).to_url) * '/'
  end
 
  def feed_url_for(section)
    "/feed/#{sections(section).to_feed_url * '/'}"
  end
end
 
class ActionController::Integration::Session
  def login_as(login)
    post 'http://test.host/account/login', :login => login, :password => 'test'
    assert request.session[:user]
    assert redirect?
  end
 
  def get_with_basic(url, options = {})
    get url, nil, 'authorization' => "Basic #{Base64.encode64("#{options[:login]}:test")}"
  end
 
  def assert_redirected_to(url)
    assert redirect?
    assert_equal url, interpret_uri(headers["location"].first)
  end
 
  def assert_redirected_to!(url)
    assert_redirected_to(url)
    follow_redirect!
  end
end
 
class BaseLoginProxy
  attr_reader :controller
  attr_reader :options
  def initialize(controller, login)
    @controller = controller
    @login = login
  end
 
  private
    def authenticated
      raise NotImplementedError
    end
    
    def check
      raise NotImplementedError
    end
    
    def method_missing(method, *args)
      @controller.reset!
      authenticate
      @controller.send(method, *args)
      check
    end
end
 
class HttpLoginProxy < BaseLoginProxy
  protected
    def authenticate
      @controller.login_as @login if @login
    end
    
    def check
      @controller.assert_redirected_to :controller => 'sessions', :action => 'new'
    end
end
 
class XmlLoginProxy < BaseLoginProxy
  protected
    def authenticate
      @controller.accept 'application/xml'
      @controller.authorize_as @login if @login
    end
    
    def check
      @controller.assert_response 401
    end
end
 
 
#module Mephisto
# module Plugins
# class PluginWhammyJammy < Mephisto::Plugin
# option :foo, 'one'
# option :bar, 2
# option :baz, [3]
# end
#
# class FooBar < Mephisto::Plugin
# end
#
# class NonPlugin
# end
# end
#end
 
begin
  require 'ruby-debug'
  Debugger.start
rescue LoadError
end