padrino-admin 0.18.0 → 0.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. checksums.yaml +4 -4
  2. data/lib/padrino-admin/generators/actions.rb +1 -0
  3. data/lib/padrino-admin/generators/admin_app.rb +36 -17
  4. data/lib/padrino-admin/generators/admin_page.rb +2 -1
  5. data/lib/padrino-admin/generators/keep_files.rb +56 -0
  6. data/lib/padrino-admin/generators/orm.rb +16 -2
  7. data/lib/padrino-admin/generators/templates/account/mongoid.rb.tt +1 -1
  8. data/lib/padrino-admin/generators/templates/app/controllers/sessions.rb.tt +0 -4
  9. data/lib/padrino-admin/generators/templates/assets/stylesheets/application.css +0 -3
  10. data/lib/padrino-admin/generators/templates/erb/app/layouts/application.erb.tt +0 -5
  11. data/lib/padrino-admin/generators/templates/erb/app/layouts/error.erb.tt +0 -5
  12. data/lib/padrino-admin/generators/templates/erb/app/sessions/new.erb.tt +0 -10
  13. data/lib/padrino-admin/generators/templates/erb/page/index.erb.tt +2 -2
  14. data/lib/padrino-admin/generators/templates/haml/app/layouts/application.haml.tt +0 -5
  15. data/lib/padrino-admin/generators/templates/haml/app/layouts/error.haml.tt +0 -5
  16. data/lib/padrino-admin/generators/templates/haml/app/sessions/new.haml.tt +0 -10
  17. data/lib/padrino-admin/generators/templates/haml/page/index.haml.tt +2 -2
  18. data/lib/padrino-admin/generators/templates/page/controller.rb.tt +0 -3
  19. data/lib/padrino-admin/generators/templates/slim/app/layouts/application.slim.tt +0 -5
  20. data/lib/padrino-admin/generators/templates/slim/app/layouts/error.slim.tt +0 -5
  21. data/lib/padrino-admin/generators/templates/slim/app/sessions/new.slim.tt +0 -10
  22. data/lib/padrino-admin/generators/templates/slim/page/index.slim.tt +2 -2
  23. data/lib/padrino-admin/helpers/authentication_helpers.rb +3 -1
  24. data/lib/padrino-admin.rb +21 -1
  25. data/padrino-admin.gemspec +8 -3
  26. data/test/generators/test_admin_app_generator.rb +54 -0
  27. data/test/generators/test_admin_page_generator.rb +130 -4
  28. data/test/generators/test_admin_rerun_generator.rb +244 -0
  29. data/test/test_admin_application.rb +73 -0
  30. metadata +15 -9
@@ -16,6 +16,13 @@ describe 'AdminAppGenerator' do
16
16
  Object.send(:remove_const, :Account) if defined?(Account)
17
17
  end
18
18
 
19
+ it 'should stop with a message in a project without an app' do
20
+ capture_io { generate(:project, 'sample_project', '--lean', "--root=#{@apptmp}", '-d', 'sequel', '-e', 'erb') }
21
+ out, = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_app, "-r=#{@apptmp}/sample_project") }.status }
22
+ assert_match(/Unable to locate 'App' application/, out)
23
+ refute_path_exists "#{@apptmp}/sample_project/admin"
24
+ end
25
+
19
26
  it 'should fail outside app root' do
20
27
  out, = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_app, "-r=#{@apptmp}") }.status }
21
28
  assert_match(/not at the root/, out)
@@ -261,9 +268,56 @@ describe 'AdminAppGenerator' do
261
268
  assert_equal '200', code, "#{page} includes #{src}, which is not served"
262
269
  end
263
270
  end
271
+
272
+ it "should load only the admin's own assets on the #{engine} admin pages, with no IE conditional comments" do
273
+ skip 'the sqlite3 gem is only bundled on MRI' if RUBY_ENGINE == 'jruby'
274
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', "-e=#{engine}") }
275
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
276
+ script = <<~'RUBY'
277
+ ENV['RACK_ENV'] = 'test'
278
+ %w[sequel haml slim erubi nokogiri rack/test].each { |lib| require lib }
279
+ Sequel.extension :migration
280
+ Sequel.sqlite('db/sample_project_test.db') { |db| Sequel::Migrator.run(db, 'db/migrate') }
281
+ require File.expand_path('config/boot')
282
+ account_id = Account.dataset.insert(email: 'admin@example.com', role: 'admin', crypted_password: 'unused')
283
+
284
+ browser = Rack::Test::Session.new(Padrino.application)
285
+ check = lambda do |page|
286
+ browser.get(page)
287
+ puts "PAGE #{page} #{browser.last_response.status}"
288
+ html = Nokogiri::HTML(browser.last_response.body)
289
+ html.css('link[href], script[src]').each { |tag| puts "ASSET #{page} #{tag['href'] || tag['src']}" }
290
+ html.xpath('//comment()').each { |comment| puts "COMMENT #{page} #{comment.text.split.join(' ')}" }
291
+ end
292
+ check.call('/admin/sessions/new')
293
+ browser.env('rack.session', SampleProject::Admin.session_id => account_id)
294
+ check.call('/admin/')
295
+ check.call('/admin/accounts/edit/0')
296
+ RUBY
297
+ env = { 'BUNDLE_GEMFILE' => File.expand_path('../../../Gemfile', __dir__) }
298
+ out, err, status = Open3.capture3(env, RbConfig.ruby, '-rbundler/setup', '-e', script, chdir: "#{@apptmp}/sample_project")
299
+ assert status.success?, err
300
+ statuses = out.lines.grep(/\APAGE /).map { |line| line.split[1, 2] }
301
+ assert_equal [['/admin/sessions/new', '200'], ['/admin/', '200'], ['/admin/accounts/edit/0', '404']], statuses
302
+ assets = out.lines.grep(/\AASSET /).map(&:split)
303
+ refute_empty assets
304
+ assets.each do |(_, page, url)|
305
+ assert_match %r{\A/(?!/)}, url, "#{page} loads #{url} from another site"
306
+ end
307
+ assert_empty out.lines.grep(/\ACOMMENT .*\[if /)
308
+ end
264
309
  end
265
310
  end
266
311
 
312
+ it 'should name in the admin stylesheet only fonts it loads itself' do
313
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', '-e=erb') }
314
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
315
+ stylesheet = File.read("#{@apptmp}/sample_project/public/admin/stylesheets/application.css")
316
+ loaded = stylesheet.scan(/@font-face\s*\{\s*font-family:\s*['"]([^'"]+)['"]/).flatten
317
+ named = stylesheet.scan(/font-family:([^;}]+)/).flatten.flat_map { |list| list.split(',') }.map { |font| font.strip.delete(%q('")) }
318
+ assert_empty named.uniq - loaded - %w[serif sans-serif monospace system-ui inherit]
319
+ end
320
+
267
321
  it 'should correctly generate a new padrino admin application with a custom model' do
268
322
  capture_io { generate(:project, 'sample_project', '-e=slim', "--root=#{@apptmp}", '-d=activerecord', '-e=slim') }
269
323
  capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project", '-m=User') }
@@ -1,6 +1,7 @@
1
1
  require_relative '../helper'
2
2
  require_relative '../fixtures/sequel'
3
3
  require 'nokogiri'
4
+ require 'padrino-gen/generators/cli'
4
5
 
5
6
  describe 'AdminPageGenerator' do
6
7
  before do
@@ -13,6 +14,12 @@ describe 'AdminPageGenerator' do
13
14
  end
14
15
 
15
16
  describe 'the admin page generator' do
17
+ it 'should stop with a message in a project without an app' do
18
+ capture_io { generate(:project, 'sample_project', '--lean', "--root=#{@apptmp}", '-d', 'sequel', '-e', 'erb') }
19
+ out, = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_page, 'foo', "-r=#{@apptmp}/sample_project") }.status }
20
+ assert_match(/Unable to locate 'App' application/, out)
21
+ end
22
+
16
23
  it 'should fail outside app root' do
17
24
  out, = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_page, 'foo', "-r=#{@apptmp}/sample_project") }.status }
18
25
  assert_match(/not at the root/, out)
@@ -48,6 +55,17 @@ describe 'AdminPageGenerator' do
48
55
  assert_no_match_in_file(/project_module :foos/, "#{@apptmp}/sample_project/admin/app.rb")
49
56
  end
50
57
 
58
+ it 'should fail without an existent model whose name repeats a namespace' do
59
+ capture_io { generate(:project, 'sample_project', '-e=slim', "--root=#{@apptmp}", '-d=sequel') }
60
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
61
+ Object.const_set(:RepeatedPageShop, Module.new)
62
+ RepeatedPageShop.const_set(:Order, Module.new)
63
+ _, err = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_page, 'repeated_page_shop/order/order', "-r=#{@apptmp}/sample_project") }.status }
64
+ assert_match(/Model 'RepeatedPageShop::Order::Order' could not be found/, err)
65
+ ensure
66
+ Object.send(:remove_const, :RepeatedPageShop) if Object.const_defined?(:RepeatedPageShop, false)
67
+ end
68
+
51
69
  %w[erb haml slim].each do |renderer|
52
70
  it "should destroy pages whose models were already removed (#{renderer})" do
53
71
  Object.const_set(:GoneWidget, Class.new(Sequel::Model(:friends)))
@@ -95,6 +113,31 @@ describe 'AdminPageGenerator' do
95
113
  assert_no_dir_exists("#{@apptmp}/sample_project/admin/views/friends")
96
114
  end
97
115
 
116
+ it 'should report a model that fails to load with the project instead of a missing one' do
117
+ capture_io { generate(:project, 'sample_project', '-e=slim', "--root=#{@apptmp}", '-d=sequel') }
118
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
119
+ File.write("#{@apptmp}/sample_project/models/broken_widget.rb", "class BrokenWidget < Sequel::Modle; end\n")
120
+ File.write("#{@apptmp}/sample_project/config/boot.rb", "require_relative '../models/broken_widget'\n")
121
+ capture_io { Padrino::Generators::Cli.new([], root: "#{@apptmp}/sample_project").load_boot }
122
+ _, err = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_page, 'broken_widget', "-r=#{@apptmp}/sample_project") }.status }
123
+ assert_match(/Model 'BrokenWidget' could not be loaded because the project failed to load!\nNameError: uninitialized constant Sequel::Modle/, err)
124
+ refute_match(/could not be found/, err)
125
+ assert_no_dir_exists("#{@apptmp}/sample_project/admin/views/broken_widgets")
126
+ ensure
127
+ Padrino::Generators.boot_error = nil
128
+ end
129
+
130
+ it 'should report the error of a model that fails to load when looked up' do
131
+ capture_io { generate(:project, 'sample_project', '-e=slim', "--root=#{@apptmp}", '-d=sequel') }
132
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
133
+ File.write("#{@apptmp}/broken_page_sample.rb", "module BrokenPageSample; class Gadget; MissingConcern; end; end\n")
134
+ Object.autoload(:BrokenPageSample, "#{@apptmp}/broken_page_sample.rb")
135
+ _, err = capture_io { assert_equal 1, assert_raises(SystemExit) { generate(:admin_page, 'broken_page_sample/gadget', "-r=#{@apptmp}/sample_project") }.status }
136
+ assert_match(/Model 'BrokenPageSample::Gadget' could not be loaded!\nNameError: uninitialized constant BrokenPageSample::Gadget::MissingConcern/, err)
137
+ ensure
138
+ Object.send(:remove_const, :BrokenPageSample) if Object.const_defined?(:BrokenPageSample, false)
139
+ end
140
+
98
141
  it 'should fail when the project has no orm and the model is not activerecord' do
99
142
  capture_io { generate(:project, 'sample_project', '-e=slim', "--root=#{@apptmp}", '-d=sequel') }
100
143
  capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
@@ -111,7 +154,7 @@ describe 'AdminPageGenerator' do
111
154
  assert_file_exists "#{@apptmp}/sample_project/admin/controllers/friends.rb"
112
155
  assert_match_in_file 'SampleProject::Admin.controllers :friends do', "#{@apptmp}/sample_project/admin/controllers/friends.rb"
113
156
  assert_match_in_file "role.project_module :friends, '/friends'", "#{@apptmp}/sample_project/admin/app.rb"
114
- assert_match_in_file 'elsif Padrino.env == :development && params[:bypass]', "#{@apptmp}/sample_project/admin/controllers/sessions.rb"
157
+ assert_no_match_in_file(/bypass/, "#{@apptmp}/sample_project/admin/controllers/sessions.rb")
115
158
  end
116
159
 
117
160
  # users can override certain templates from a generators/templates folder in the destination_root
@@ -137,7 +180,7 @@ describe 'AdminPageGenerator' do
137
180
  assert_match_in_file "label :#{field}", "#{@apptmp}/sample_project/admin/views/friends/_form.haml"
138
181
  assert_match_in_file "text_field :#{field}", "#{@apptmp}/sample_project/admin/views/friends/_form.haml"
139
182
  end
140
- assert_match_in_file 'check_box_tag :bypass', "#{@apptmp}/sample_project/admin/views/sessions/new.haml"
183
+ assert_no_match_in_file(/bypass/, "#{@apptmp}/sample_project/admin/views/sessions/new.haml")
141
184
  end
142
185
 
143
186
  it 'should correctly generate a new page with erb' do
@@ -152,7 +195,7 @@ describe 'AdminPageGenerator' do
152
195
  assert_match_in_file "label :#{field}", "#{@apptmp}/sample_project/admin/views/friends/_form.erb"
153
196
  assert_match_in_file "text_field :#{field}", "#{@apptmp}/sample_project/admin/views/friends/_form.erb"
154
197
  end
155
- assert_match_in_file 'check_box_tag :bypass', "#{@apptmp}/sample_project/admin/views/sessions/new.erb"
198
+ assert_no_match_in_file(/bypass/, "#{@apptmp}/sample_project/admin/views/sessions/new.erb")
156
199
  end
157
200
 
158
201
  it 'should correctly generate a new page with slim' do
@@ -167,7 +210,7 @@ describe 'AdminPageGenerator' do
167
210
  assert_match_in_file "label :#{field}", "#{@apptmp}/sample_project/admin/views/friends/_form.slim"
168
211
  assert_match_in_file "text_field :#{field}", "#{@apptmp}/sample_project/admin/views/friends/_form.slim"
169
212
  end
170
- assert_match_in_file 'check_box_tag :bypass', "#{@apptmp}/sample_project/admin/views/sessions/new.slim"
213
+ assert_no_match_in_file(/bypass/, "#{@apptmp}/sample_project/admin/views/sessions/new.slim")
171
214
  end
172
215
  end
173
216
 
@@ -197,6 +240,89 @@ describe 'AdminPageGenerator' do
197
240
  assert_equal %w[list-menu-wrapper list-menu-wrapper-disabled], classes.call(page.at_css(link).parent)
198
241
  end
199
242
  end
243
+
244
+ # Mongoid reports a boolean field's type as the class Mongoid::Boolean, not as :boolean.
245
+ [nil, 'Mongoid::Boolean'].each do |type_name|
246
+ it "should show boolean columns in the list as icons the stylesheet draws (#{renderer}#{", #{type_name}" if type_name})" do
247
+ Sequel::Model.db.create_table!(:switches) do
248
+ primary_key :id
249
+ String :name
250
+ TrueClass :enabled
251
+ end
252
+ # JRuby's jdbc-sqlite stores booleans as integers and loads 0 as 0, which is truthy.
253
+ Object.const_set(:Switch, Class.new(Sequel::Model(:switches)) { plugin :typecast_on_load, :enabled })
254
+ Switch.create(name: 'on', enabled: true)
255
+ Switch.create(name: 'off', enabled: false)
256
+ Switch.create(name: 'unset', enabled: nil)
257
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', "-e=#{renderer}") }
258
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
259
+ if type_name
260
+ boolean = Class.new
261
+ boolean.define_singleton_method(:to_s) { type_name }
262
+ columns = Switch.db_schema.map { |name, info| Padrino::Admin::Generators::Orm::Column.new(name, name == :enabled ? boolean : info[:type]) }
263
+ Padrino::Admin::Generators::Orm.any_instance.stubs(:columns).returns(columns)
264
+ end
265
+ capture_io { generate(:admin_page, 'switch', "--root=#{@apptmp}/sample_project") }
266
+ views = "#{@apptmp}/sample_project/admin/views"
267
+ mock_app do
268
+ set :views, views
269
+ helpers Padrino::Admin::Helpers::ViewHelpers
270
+ controllers :switches do
271
+ get(:index) do
272
+ @switches = Switch.order(:id).all
273
+ render 'switches/index', layout: false
274
+ end
275
+ get(:new) {}
276
+ get(:edit, with: :id) {}
277
+ delete(:destroy, with: :id) {}
278
+ delete(:destroy_many) {}
279
+ end
280
+ end
281
+ get '/switches'
282
+ assert_equal 200, last_response.status
283
+ page = Nokogiri::HTML(last_response.body)
284
+ column = page.css('#list thead th').map { |th| th.text.strip }.index('Enabled')
285
+ on, off, unset = page.css('#list tbody tr').map { |row| row.css('td')[column] }
286
+ icons = ->(cell) { cell.css('i.fa').flat_map { |icon| icon['class'].split - ['fa'] } }
287
+ refute_empty icons.call(on)
288
+ refute_empty icons.call(off)
289
+ refute_equal icons.call(on), icons.call(off)
290
+ assert_equal 'true', on.at_css('.sr-only')&.text
291
+ assert_equal 'false', off.at_css('.sr-only')&.text
292
+ assert_empty unset.children.to_s.strip
293
+ stylesheet = File.read("#{@apptmp}/sample_project/public/admin/stylesheets/application.css")
294
+ undrawn = (icons.call(on) + icons.call(off)).reject { |icon| stylesheet.include?(".#{icon}:before") }
295
+ assert_empty undrawn, 'the stylesheet draws no glyph for these icons'
296
+ ensure
297
+ Object.send(:remove_const, :Switch) if Object.const_defined?(:Switch, false)
298
+ Sequel::Model.db.drop_table?(:switches)
299
+ end
300
+ end
301
+ end
302
+
303
+ it 'should not carry a flash over to the next page when a record is not found' do
304
+ saved = Object.send(:remove_const, :SampleProject) if Object.const_defined?(:SampleProject, false)
305
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', '-e=erb') }
306
+ capture_io { generate(:admin_app, "--root=#{@apptmp}/sample_project") }
307
+ capture_io { generate(:admin_page, 'friend', "--root=#{@apptmp}/sample_project") }
308
+ mock_app do
309
+ enable :sessions
310
+ helpers Padrino::Admin::Helpers::ViewHelpers
311
+ get(:flash) { flash.keys.join(',') }
312
+ end
313
+ Object.const_set(:SampleProject, Module.new).const_set(:Admin, @app)
314
+ load "#{@apptmp}/sample_project/admin/controllers/friends.rb"
315
+ get '/friends/edit/999'
316
+ assert_equal 404, last_response.status
317
+ put '/friends/update/999'
318
+ assert_equal 404, last_response.status
319
+ delete '/friends/destroy/999'
320
+ assert_equal 404, last_response.status
321
+ get '/flash'
322
+ assert_equal '', last_response.body
323
+ ensure
324
+ Object.send(:remove_const, :SampleProject) if Object.const_defined?(:SampleProject, false)
325
+ Object.const_set(:SampleProject, saved) if saved
200
326
  end
201
327
 
202
328
  it 'should correctly generate a new padrino admin application with multiple models at the same time' do
@@ -0,0 +1,244 @@
1
+ require_relative '../helper'
2
+ require_relative '../fixtures/sequel'
3
+
4
+ describe 'AdminRerun' do
5
+ before do
6
+ @apptmp = "#{Dir.tmpdir}/padrino-tests/#{SecureRandom.hex}"
7
+ `mkdir -p #{@apptmp}`
8
+ @project = "#{@apptmp}/sample_project"
9
+ end
10
+
11
+ after do
12
+ `rm -rf #{@apptmp}`
13
+ end
14
+
15
+ # Thor reads each answer through its line editor, which returns nil at the end of input.
16
+ def with_answers(*answers)
17
+ Thor::LineEditor.stubs(:readline).returns(*answers, nil)
18
+ yield
19
+ end
20
+
21
+ def with_stdin(input)
22
+ original = $stdin
23
+ $stdin = StringIO.new(input)
24
+ yield
25
+ ensure
26
+ $stdin = original
27
+ end
28
+
29
+ def edit(file)
30
+ path = "#{@project}/#{file}"
31
+ File.write(path, "#{yield(File.read(path))}\n# edited\n")
32
+ end
33
+
34
+ def snapshot
35
+ Dir.glob("#{@project}/**/*", File::FNM_DOTMATCH).select { |path| File.file?(path) }.to_h { |path| [path, File.read(path)] }
36
+ end
37
+
38
+ %w[activerecord mongoid sequel].each do |orm|
39
+ describe "with #{orm}" do
40
+ before do
41
+ Object.send(:remove_const, :Account) if defined?(Account)
42
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", "-d=#{orm}", '-e=haml') }
43
+ capture_io { generate(:admin_app, "--root=#{@project}") }
44
+ %w[models/account.rb db/seeds.rb admin/controllers/accounts.rb admin/views/base/index.haml public/admin/stylesheets/application.css].each do |file|
45
+ edit(file) { |content| content }
46
+ end
47
+ edit('admin/app.rb') { |content| content.sub("'/accounts'", "'/accounts' # staff only") }
48
+ edit('config/apps.rb') { |content| content.sub(".to('/admin')", ".to('/backend')") }
49
+ edit('Gemfile') { |content| content.sub("gem 'bcrypt'", "gem 'bcrypt', '>= 3.1'") }
50
+ end
51
+
52
+ it 'should keep edited files when g admin runs again at the end of input' do
53
+ edited = snapshot
54
+ out, = capture_io { with_answers { generate(:admin_app, "--root=#{@project}") } }
55
+ assert_equal edited, snapshot
56
+ assert_match(%r{skip\s+admin/app\.rb}, out)
57
+ end
58
+
59
+ it 'should still overwrite a file when the conflict is answered with yes' do
60
+ capture_io { with_answers(*['y'] * 50) { generate(:admin_app, "--root=#{@project}") } }
61
+ assert_no_match_in_file(/# edited/, "#{@project}/models/account.rb")
62
+ assert_no_match_in_file(/# edited/, "#{@project}/admin/controllers/accounts.rb")
63
+ assert_match_in_file(/# edited/, "#{@project}/config/apps.rb")
64
+ end
65
+
66
+ it 'should keep the lines of app.rb when a yes rewrites it' do
67
+ capture_io { with_answers(*['y'] * 50) { generate(:admin_app, "--root=#{@project}") } }
68
+ app = "#{@project}/admin/app.rb"
69
+ assert_no_match_in_file(/# edited/, app)
70
+ assert_match_in_file(%r{role\.project_module :accounts, '/accounts'}, app)
71
+ orm == 'activerecord' ? assert_match_in_file(/use ConnectionPoolManagement/, app) : assert_no_match_in_file(/ConnectionPoolManagement/, app)
72
+ assert_match_in_file(/account != current_account && account\.destroy/, "#{@project}/admin/controllers/accounts.rb")
73
+ end
74
+
75
+ it 'should keep edited seeds that delegate to another file at the end of input' do
76
+ File.write("#{@project}/db/seeds.rb", "load 'db/seeds/staff.rb'\n")
77
+ edited = snapshot
78
+ capture_io { with_answers { generate(:admin_app, "--root=#{@project}") } }
79
+ assert_equal edited, snapshot
80
+ end
81
+
82
+ it 'should send delegating seeds through the overwrite prompt' do
83
+ File.write("#{@project}/db/seeds.rb", "load 'db/seeds/staff.rb'\n")
84
+ capture_io { with_answers(*['y'] * 50) { generate(:admin_app, "--root=#{@project}") } }
85
+ assert_match_in_file(/Account\.new\(/, "#{@project}/db/seeds.rb")
86
+ assert_no_file_exists("#{@project}/db/seeds.old")
87
+ end
88
+
89
+ it 'should move seeds without the model aside for the first install of another admin app' do
90
+ File.write("#{@project}/db/seeds.rb", "load 'db/seeds/staff.rb'\n")
91
+ capture_io { with_answers { generate(:admin_app, "--root=#{@project}", '-a=other') } }
92
+ assert_match_in_file(/staff\.rb/, "#{@project}/db/seeds.old")
93
+ assert_match_in_file(/Account\.new\(/, "#{@project}/db/seeds.rb")
94
+ end
95
+
96
+ it 'should keep gems declared with parentheses' do
97
+ edit('Gemfile') do |content|
98
+ content.sub(/^gem 'bcrypt'.*$/, "gem('bcrypt', '>= 3.1')").sub(/^gem 'activesupport'.*$/, "gem('activesupport', '>= 3.1')")
99
+ end
100
+ edited = snapshot
101
+ capture_io { with_answers { generate(:admin_app, "--root=#{@project}") } }
102
+ assert_equal edited, snapshot
103
+ assert_equal 1, File.read("#{@project}/Gemfile").scan(/bcrypt/).size
104
+ assert_equal 1, File.read("#{@project}/Gemfile").scan(/activesupport/).size
105
+ end
106
+
107
+ it 'should not stop a re-run for a model that gets authenticate elsewhere' do
108
+ File.write("#{@project}/models/account.rb", "class Account\n extend Credentials\nend\n")
109
+ edited = snapshot
110
+ capture_io do
111
+ with_stdin('') do
112
+ with_answers { generate(:admin_app, "--root=#{@project}") }
113
+ rescue SystemExit => e
114
+ flunk "the admin generator exited with status #{e.status}"
115
+ end
116
+ end
117
+ assert_equal edited, snapshot
118
+ end
119
+
120
+ it 'should leave a removed destroy guard removed at the end of input' do
121
+ edit('admin/controllers/accounts.rb') { |content| content.sub('account != current_account && ', '') }
122
+ edited = snapshot
123
+ capture_io { with_answers { generate(:admin_app, "--root=#{@project}") } }
124
+ assert_equal edited, snapshot
125
+ end
126
+ end
127
+
128
+ describe "with #{orm} and an account model that can't log in" do
129
+ before do
130
+ Object.send(:remove_const, :Account) if defined?(Account)
131
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", "-d=#{orm}", '-e=haml') }
132
+ FileUtils.mkdir_p("#{@project}/models")
133
+ File.write("#{@project}/models/account.rb", "class Account\nend\n")
134
+ end
135
+
136
+ it 'should stop before writing anything at the end of input' do
137
+ before_run = snapshot
138
+ _, err = capture_io do
139
+ with_stdin('') { assert_equal 1, assert_raises(SystemExit) { generate(:admin_app, "--root=#{@project}") }.status }
140
+ end
141
+ assert_match(/no authenticate method/, err)
142
+ assert_equal before_run, snapshot
143
+ end
144
+
145
+ it 'should replace the model when the prompt is answered with yes' do
146
+ capture_io { with_stdin("y\n") { with_answers(*['y'] * 50) { generate(:admin_app, "--root=#{@project}") } } }
147
+ assert_match_in_file(/def self\.authenticate/, "#{@project}/models/account.rb")
148
+ end
149
+ end
150
+
151
+ describe "with #{orm} and an admin app that only partly exists" do
152
+ before do
153
+ Object.send(:remove_const, :Account) if defined?(Account)
154
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", "-d=#{orm}", '-e=haml') }
155
+ end
156
+
157
+ it 'should add the missing lines at the end of input and keep a partial app.rb' do
158
+ FileUtils.mkdir_p("#{@project}/admin")
159
+ File.write("#{@project}/admin/app.rb", "# partial\n")
160
+ capture_io { with_answers { generate(:admin_app, "--root=#{@project}") } }
161
+ assert_equal "# partial\n", File.read("#{@project}/admin/app.rb")
162
+ assert_match_in_file(%r{Padrino\.mount\('SampleProject::Admin'.*\.to\('/admin'\)}, "#{@project}/config/apps.rb")
163
+ assert_match_in_file(/gem 'bcrypt'/, "#{@project}/Gemfile")
164
+ end
165
+
166
+ it 'should stop for a plain model after g app admin at the end of input' do
167
+ capture_io { generate(:app, 'admin', "-r=#{@project}") }
168
+ FileUtils.mkdir_p("#{@project}/models")
169
+ File.write("#{@project}/models/account.rb", "class Account\nend\n")
170
+ before_run = snapshot
171
+ capture_io do
172
+ with_stdin('') { assert_equal 1, assert_raises(SystemExit) { generate(:admin_app, "--root=#{@project}") }.status }
173
+ end
174
+ assert_equal before_run, snapshot
175
+ end
176
+
177
+ it 'should add every line after g app admin and a yes' do
178
+ capture_io { generate(:app, 'admin', "-r=#{@project}") }
179
+ capture_io { with_answers(*['y'] * 50) { generate(:admin_app, "--root=#{@project}") } }
180
+ assert_match_in_file(/gem 'bcrypt'/, "#{@project}/Gemfile")
181
+ assert_match_in_file(/gem 'activesupport'/, "#{@project}/Gemfile")
182
+ assert_equal 1, File.read("#{@project}/config/apps.rb").scan(/^Padrino\.mount\('SampleProject::Admin'/).size
183
+ assert_match_in_file(%r{role\.project_module :accounts, '/accounts'}, "#{@project}/admin/app.rb")
184
+ end
185
+ end
186
+ end
187
+
188
+ describe 'the admin page generator' do
189
+ before do
190
+ capture_io { generate(:project, 'sample_project', "--root=#{@apptmp}", '-d=sequel', '-e=haml') }
191
+ capture_io { generate(:admin_app, "--root=#{@project}") }
192
+ capture_io { with_answers { generate(:admin_page, 'section', "-r=#{@project}") } }
193
+ end
194
+
195
+ it 'should add the permission of a new page at the end of input' do
196
+ assert_match_in_file(%r{role\.project_module :sections, '/sections'}, "#{@project}/admin/app.rb")
197
+ end
198
+
199
+ it 'should add the permission when the controller came from g controller' do
200
+ capture_io { generate(:controller, 'widgets', '-a=admin', "-r=#{@project}") }
201
+ Object.const_set(:Widget, Class.new(Sequel::Model(:sections)))
202
+ capture_io { with_answers { generate(:admin_page, 'widget', "-r=#{@project}") } }
203
+ assert_match_in_file(%r{role\.project_module :widgets, '/widgets'}, "#{@project}/admin/app.rb")
204
+ ensure
205
+ Object.send(:remove_const, :Widget) if defined?(Widget)
206
+ end
207
+
208
+ it 'should keep edited files when it runs again at the end of input' do
209
+ edit('admin/controllers/sections.rb') { |content| content }
210
+ edit('admin/views/sections/index.haml') { |content| content }
211
+ edit('admin/app.rb') { |content| content.sub("'/sections'", "'/sections' # staff only") }
212
+ edited = snapshot
213
+ capture_io { with_answers { generate(:admin_page, 'section', "-r=#{@project}") } }
214
+ assert_equal edited, snapshot
215
+ end
216
+
217
+ describe 'with a piped answer' do
218
+ before do
219
+ @controller = "#{@project}/admin/controllers/sections.rb"
220
+ File.write(@controller, "# edited\n")
221
+ end
222
+
223
+ def rerun_answering(answer)
224
+ capture_io { with_answers(answer) { generate(:admin_page, 'section', "-r=#{@project}") } }
225
+ end
226
+
227
+ it 'should overwrite the file when the answer is yes' do
228
+ rerun_answering('y')
229
+ assert_no_match_in_file(/# edited/, @controller)
230
+ end
231
+
232
+ it 'should keep the file when the answer is no' do
233
+ rerun_answering('n')
234
+ assert_equal "# edited\n", File.read(@controller)
235
+ end
236
+
237
+ it 'should keep the file when input runs out after asking for the diff' do
238
+ Thor::Shell::Basic.any_instance.stubs(:show_diff)
239
+ rerun_answering('d')
240
+ assert_equal "# edited\n", File.read(@controller)
241
+ end
242
+ end
243
+ end
244
+ end
@@ -402,6 +402,79 @@ describe 'AdminApplication' do
402
402
  assert_raises(Padrino::Admin::AccessControlError) { access_control.roles_for }
403
403
  end
404
404
 
405
+ describe 'admin model' do
406
+ def mock_admin_app(admin_model)
407
+ mock_app do
408
+ register Padrino::Admin::AccessControl
409
+ set :admin_model, admin_model
410
+ get('/current') { current_account.inspect }
411
+ end
412
+ end
413
+
414
+ it 'should say a missing admin model must be defined' do
415
+ mock_admin_app 'MissingAdminSample::Account'
416
+ error = assert_raises(Padrino::Admin::AccessControlError) { get '/current' }
417
+ assert_equal 'You must define an MissingAdminSample::Account Model', error.message
418
+ end
419
+
420
+ it 'should say a missing admin model must be defined when its name repeats a namespace' do
421
+ Object.const_set(:RepeatedAdminSample, Module.new)
422
+ mock_admin_app 'RepeatedAdminSample::RepeatedAdminSample'
423
+ error = assert_raises(Padrino::Admin::AccessControlError) { get '/current' }
424
+ assert_equal 'You must define an RepeatedAdminSample::RepeatedAdminSample Model', error.message
425
+ ensure
426
+ Object.send(:remove_const, :RepeatedAdminSample) if Object.const_defined?(:RepeatedAdminSample, false)
427
+ end
428
+
429
+ it 'should raise the error of a top-level admin model whose body names another constant like it' do
430
+ Dir.mktmpdir do |dir|
431
+ File.write("#{dir}/colliding_top_account.rb", <<~RUBY)
432
+ module CollidingTopMixins; end
433
+ class CollidingTopAccount
434
+ include CollidingTopMixins::CollidingTopAccount
435
+ end
436
+ RUBY
437
+ Object.autoload(:CollidingTopAccount, "#{dir}/colliding_top_account.rb")
438
+ mock_admin_app 'CollidingTopAccount'
439
+ error = assert_raises(NameError) { get '/current' }
440
+ assert_match(/CollidingTopMixins::CollidingTopAccount/, error.message)
441
+ end
442
+ ensure
443
+ %i[CollidingTopAccount CollidingTopMixins].each { |name| Object.send(:remove_const, name) if Object.const_defined?(name, false) }
444
+ end
445
+
446
+ it 'should raise the error of an admin model whose body names another constant like it' do
447
+ Dir.mktmpdir do |dir|
448
+ File.write("#{dir}/colliding_admin_sample.rb", <<~RUBY)
449
+ module CollidingAdminSample
450
+ module Mixins; end
451
+ class Account
452
+ include Mixins::Account
453
+ end
454
+ end
455
+ RUBY
456
+ Object.autoload(:CollidingAdminSample, "#{dir}/colliding_admin_sample.rb")
457
+ mock_admin_app 'CollidingAdminSample::Account'
458
+ error = assert_raises(NameError) { get '/current' }
459
+ assert_match(/Mixins::Account/, error.message)
460
+ end
461
+ ensure
462
+ Object.send(:remove_const, :CollidingAdminSample) if Object.const_defined?(:CollidingAdminSample, false)
463
+ end
464
+
465
+ it 'should raise the error of an admin model that fails to load' do
466
+ Dir.mktmpdir do |dir|
467
+ File.write("#{dir}/broken_admin_sample.rb", "module BrokenAdminSample; class Account; MissingConcern; end; end\n")
468
+ Object.autoload(:BrokenAdminSample, "#{dir}/broken_admin_sample.rb")
469
+ mock_admin_app 'BrokenAdminSample::Account'
470
+ error = assert_raises(NameError) { get '/current' }
471
+ assert_match(/MissingConcern/, error.message)
472
+ end
473
+ ensure
474
+ Object.send(:remove_const, :BrokenAdminSample) if Object.const_defined?(:BrokenAdminSample, false)
475
+ end
476
+ end
477
+
405
478
  it 'should humanize project module names without ActiveSupport' do
406
479
  assert_equal 'Blog posts', Padrino::Admin::AccessControl::ProjectModule.new(:blog_posts, '/blog_posts').human_name
407
480
  end