Commit e1f6eafd by Guillermo Guerrero Ibarra Committed by Cuong Tran

Fix offences and added test (#425)

* Fixed some offenses * Added test.
parent c407ed6a
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2016-12-14 23:38:08 +0100 using RuboCop version 0.46.0.
# on 2016-12-15 16:54:50 +0100 using RuboCop version 0.46.0.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
......@@ -36,14 +36,6 @@ Lint/AssignmentInCondition:
- 'lib/annotate/annotate_models.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: AlignWith, SupportedStyles.
# SupportedStyles: either, start_of_block, start_of_line
Lint/BlockAlignment:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 6
# Cop supports --auto-correct.
Lint/DeprecatedClassMethods:
......@@ -61,23 +53,14 @@ Lint/DuplicateMethods:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AlignWith, SupportedStyles, AutoCorrect.
# SupportedStyles: keyword, variable, start_of_line
Lint/EndAlignment:
Exclude:
- 'lib/annotate.rb'
# Offense count: 1
Lint/HandleExceptions:
Exclude:
- 'bin/annotate'
# Offense count: 9
# Offense count: 8
Lint/IneffectiveAccessModifier:
Exclude:
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/common_validation.rb'
# Offense count: 1
# Cop supports --auto-correct.
......@@ -87,12 +70,10 @@ Lint/InheritException:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 8
# Offense count: 5
Lint/RescueException:
Exclude:
- 'Rakefile'
- 'bin/annotate'
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
# Offense count: 1
......@@ -107,12 +88,11 @@ Lint/UnusedBlockArgument:
Exclude:
- 'bin/annotate'
# Offense count: 2
# Offense count: 1
# Configuration parameters: ContextCreatingMethods.
Lint/UselessAccessModifier:
Exclude:
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/common_validation.rb'
# Offense count: 16
Metrics/AbcSize:
......@@ -131,7 +111,7 @@ Metrics/BlockNesting:
Metrics/CyclomaticComplexity:
Max: 36
# Offense count: 347
# Offense count: 334
# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
# URISchemes: http, https
Metrics/LineLength:
......@@ -153,9 +133,7 @@ Style/AccessorMethodName:
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth.
# SupportedStyles: with_first_parameter, with_fixed_indentation
Style/AlignParameters:
Style/AlignArray:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
......@@ -167,7 +145,7 @@ Style/BarePercentLiterals:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 8
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, ProceduralMethods, FunctionalMethods, IgnoredMethods.
# SupportedStyles: line_count_based, semantic, braces_for_chaining
......@@ -177,15 +155,13 @@ Style/BarePercentLiterals:
Style/BlockDelimiters:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 4
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: braces, no_braces, context_dependent
Style/BracesAroundHashParameters:
Exclude:
- 'bin/annotate'
- 'spec/integration/rails_4.1.1/lib/tasks/auto_annotate_models.rake'
- 'spec/integration/rails_4.2.0/lib/tasks/auto_annotate_models.rake'
- 'spec/integration/standalone/config/init.rb'
......@@ -229,12 +205,6 @@ Style/ClassVars:
Exclude:
- 'lib/tasks/migrate.rake'
# Offense count: 3
# Cop supports --auto-correct.
Style/ClosingParenthesisIndentation:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: Keywords.
......@@ -264,14 +234,13 @@ Style/Documentation:
- 'lib/generators/annotate/install_generator.rb'
- 'lib/tasks/migrate.rake'
# Offense count: 11
# Offense count: 9
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: leading, trailing
Style/DotPosition:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'spec/integration/common_validation.rb'
# Offense count: 2
# Cop supports --auto-correct.
......@@ -286,14 +255,12 @@ Style/EmptyLinesAroundAccessModifier:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 8
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: empty_lines, no_empty_lines
Style/EmptyLinesAroundBlockBody:
Exclude:
- 'bin/annotate'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_2.3_with_bundler/db/schema.rb'
- 'spec/integration/rails_4.1.1/db/schema.rb'
- 'spec/integration/rails_4.2.0/db/schema.rb'
......@@ -340,7 +307,7 @@ Style/GuardClause:
- 'lib/tasks/migrate.rake'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 76
# Offense count: 58
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, UseHashRocketsWithSymbolValues, PreferHashRocketsForNonAlnumEndingSymbols.
# SupportedStyles: ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys
......@@ -354,7 +321,7 @@ Style/IfUnlessModifier:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 32
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth.
# SupportedStyles: special_inside_parentheses, consistent, align_brackets
......@@ -362,7 +329,6 @@ Style/IndentArray:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 6
# Cop supports --auto-correct.
......@@ -371,13 +337,12 @@ Style/IndentArray:
Style/IndentHash:
EnforcedStyle: consistent
# Offense count: 7
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: normal, rails
Style/IndentationConsistency:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 4
......@@ -390,7 +355,7 @@ Style/IndentationWidth:
- 'spec/integration/rails_4.2.0/app/models/sub1/sub2/sub3/event.rb'
- 'spec/integration/rails_4.2.0/app/models/task.rb'
# Offense count: 3
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: require_parentheses, require_no_parentheses, require_no_parentheses_except_multiline
......@@ -412,14 +377,6 @@ Style/MultilineBlockChain:
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: symmetrical, new_line, same_line
Style/MultilineMethodCallBraceLayout:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth.
# SupportedStyles: aligned, indented, indented_relative_to_receiver
Style/MultilineMethodCallIndentation:
......@@ -443,12 +400,11 @@ Style/MutableConstant:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
- 'spec/integration/rails_2.3_with_bundler/config/environment.rb'
# Offense count: 2
# Offense count: 1
# Cop supports --auto-correct.
Style/NegatedIf:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'spec/integration/integration_spec.rb'
# Offense count: 1
# Cop supports --auto-correct.
......@@ -485,20 +441,12 @@ Style/ParallelAssignment:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AllowSafeAssignment.
Style/ParenthesesAroundCondition:
Exclude:
- 'bin/annotate'
# Offense count: 7
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: PreferredDelimiters.
Style/PercentLiteralDelimiters:
Exclude:
- 'annotate.gemspec'
- 'spec/integration/common_validation.rb'
# Offense count: 1
# Cop supports --auto-correct.
......@@ -526,16 +474,13 @@ Style/RedundantParentheses:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 6
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: AllowMultipleReturnValues.
Style/RedundantReturn:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/common_validation.rb'
- 'spec/integration/rails_3.2.8.rb'
# Offense count: 3
# Cop supports --auto-correct.
......@@ -561,16 +506,15 @@ Style/RescueModifier:
- 'lib/annotate/annotate_models.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 3
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: AllowAsExpressionSeparator.
Style/Semicolon:
Exclude:
- 'bin/annotate'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_2.3_with_bundler/config/initializers/unified_initializer.rb'
# Offense count: 19
# Offense count: 13
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: space, no_space
......@@ -580,12 +524,10 @@ Style/SpaceAroundEqualsInParameterDefault:
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/common_validation.rb'
# Offense count: 16
# Offense count: 9
# Cop supports --auto-correct.
Style/SpaceAroundKeyword:
Exclude:
- 'spec/integration/common_validation.rb'
- 'spec/integration/integration_spec.rb'
- 'spec/integration/rails_2.3_with_bundler/Gemfile'
- 'spec/integration/rails_3.2.2/Gemfile'
- 'spec/integration/rails_3.2.8/Gemfile'
......@@ -596,16 +538,14 @@ Style/SpaceAroundKeyword:
- 'spec/integration/rails_4.2.0/Gemfile'
- 'spec/integration/standalone/Gemfile'
# Offense count: 13
# Offense count: 11
# Cop supports --auto-correct.
# Configuration parameters: AllowForAlignment.
Style/SpaceAroundOperators:
Exclude:
- 'bin/annotate'
- 'lib/annotate/annotate_models.rb'
- 'lib/tasks/annotate_models.rake'
- 'lib/tasks/annotate_routes.rake'
- 'spec/integration/integration_spec.rb'
# Offense count: 6
# Cop supports --auto-correct.
......@@ -635,13 +575,12 @@ Style/SpaceInsideBrackets:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/environment.rb'
# Offense count: 6
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SupportedStyles.
# SupportedStyles: space, no_space, compact
Style/SpaceInsideHashLiteralBraces:
Exclude:
- 'bin/annotate'
- 'lib/tasks/annotate_models.rake'
# Offense count: 4
......@@ -658,15 +597,7 @@ Style/SpaceInsideStringInterpolation:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: use_perl_names, use_english_names
Style/SpecialGlobalVars:
Exclude:
- 'bin/annotate'
# Offense count: 266
# Offense count: 252
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, ConsistentQuotesInMultiline.
# SupportedStyles: single_quotes, double_quotes
......@@ -707,7 +638,7 @@ Style/TrailingBlankLines:
- 'spec/integration/rails_4.2.0/app/models/task_observer.rb'
- 'spec/integration/rails_4.2.0/config/initializers/cookies_serializer.rb'
# Offense count: 11
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyleForMultiline, SupportedStyles.
# SupportedStyles: comma, consistent_comma, no_comma
......@@ -730,10 +661,9 @@ Style/UnneededInterpolation:
- 'bin/annotate'
- 'lib/annotate/annotate_routes.rb'
# Offense count: 9
# Offense count: 8
# Cop supports --auto-correct.
Style/UnneededPercentQ:
Exclude:
- 'annotate.gemspec'
- 'spec/integration/common_validation.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
......@@ -8,11 +8,11 @@ require 'rubygems'
begin
require 'bundler'
Bundler.setup
rescue Exception
rescue StandardError
end
here = File.expand_path(File.dirname __FILE__)
$:<< "#{here}/../lib"
$LOAD_PATH << "#{here}/../lib"
require 'optparse'
require 'annotate'
......@@ -33,7 +33,7 @@ OptionParser.new do |opts|
'Place the annotations at the top (before) or the bottom (after) of the model/test/fixture/factory/route/serializer file(s)') do |p|
ENV['position'] = p
%w(position_in_class position_in_factory position_in_fixture position_in_test position_in_routes position_in_serializer).each do |key|
ENV[key] = p unless (has_set_position[key])
ENV[key] = p unless has_set_position[key]
end
end
......@@ -192,10 +192,11 @@ OptionParser.new do |opts|
opts.on('--ignore-unknown-models', "don't display warnings for bad model files") do |values|
ENV['ignore_unknown_models'] = 'true'
end
end.parse!
options = Annotate.setup_options({is_rake: ENV['is_rake'] && !ENV['is_rake'].empty?})
options = Annotate.setup_options(
is_rake: ENV['is_rake'] && !ENV['is_rake'].empty?
)
Annotate.eager_load(options)
AnnotateModels.send(target_action, options) if Annotate.include_models?
......
......@@ -9,7 +9,7 @@ begin
# ActiveSupport 3.x...
require 'active_support/hash_with_indifferent_access'
require 'active_support/core_ext/object/blank'
rescue Exception
rescue StandardError
# ActiveSupport 2.x...
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/blank'
......@@ -35,13 +35,18 @@ module Annotate
:exclude_sti_subclasses, :ignore_unknown_models
].freeze
OTHER_OPTIONS = [
:ignore_columns, :skip_on_db_migrate, :wrapper_open, :wrapper_close, :wrapper, :routes,
:hide_limit_column_types, :hide_default_column_types, :ignore_routes, :active_admin
:ignore_columns, :skip_on_db_migrate, :wrapper_open, :wrapper_close,
:wrapper, :routes, :hide_limit_column_types, :hide_default_column_types,
:ignore_routes, :active_admin
].freeze
PATH_OPTIONS = [
:require, :model_dir, :root_dir
].freeze
def self.all_options
[POSITION_OPTIONS, FLAG_OPTIONS, PATH_OPTIONS, OTHER_OPTIONS]
end
##
# Set default values that can be overridden via environment variables.
#
......@@ -51,7 +56,7 @@ module Annotate
options = HashWithIndifferentAccess.new(options)
[POSITION_OPTIONS, FLAG_OPTIONS, PATH_OPTIONS, OTHER_OPTIONS].flatten.each do |key|
all_options.flatten.each do |key|
if options.key?(key)
default_value = if options[key].is_a?(Array)
options[key].join(',')
......@@ -97,9 +102,7 @@ module Annotate
end
def self.reset_options
[POSITION_OPTIONS, FLAG_OPTIONS, PATH_OPTIONS, OTHER_OPTIONS].flatten.each do |key|
ENV[key.to_s] = nil
end
all_options.flatten.each { |key| ENV[key.to_s] = nil }
end
def self.skip_on_migration?
......@@ -126,11 +129,14 @@ module Annotate
return if loaded_tasks
self.loaded_tasks = true
Dir[File.join(File.dirname(__FILE__), 'tasks', '**/*.rake')].each { |rake| load rake }
Dir[File.join(File.dirname(__FILE__), 'tasks', '**/*.rake')].each do |rake|
load rake
end
end
def self.load_requires(options)
options[:require].each { |path| require path } if options[:require].count > 0
options[:require].count > 0 &&
options[:require].each { |path| require path }
end
def self.eager_load(options)
......@@ -161,7 +167,7 @@ module Annotate
def self.bootstrap_rake
begin
require 'rake/dsl_definition'
rescue Exception => e
rescue StandardError => e
# We might just be on an old version of Rake...
puts e.message
exit e.status_code
......
......@@ -9,8 +9,7 @@ describe AnnotateModels do
double('IndexKeyDefinition',
name: name,
columns: columns,
unique: unique
)
unique: unique)
end
def mock_foreign_key(name, from_column, to_table, to_column = 'id', constraints = {})
......@@ -20,16 +19,14 @@ describe AnnotateModels do
to_table: to_table,
primary_key: to_column,
on_delete: constraints[:on_delete],
on_update: constraints[:on_update]
)
on_update: constraints[:on_update])
end
def mock_connection(indexes = [], foreign_keys = [])
double('Conn',
indexes: indexes,
foreign_keys: foreign_keys,
supports_foreign_keys?: true
)
supports_foreign_keys?: true)
end
def mock_class(table_name, primary_key, columns, indexes = [], foreign_keys = [])
......@@ -72,10 +69,12 @@ describe AnnotateModels do
it { expect(AnnotateModels.quote([BigDecimal.new('1.2')])).to eql(['1.2']) }
it 'should get schema info with default options' do
klass = mock_class(:users, :id, [
klass = mock_class(:users,
:id,
[
mock_column(:id, :integer, limit: 8),
mock_column(:name, :string, limit: 50),
mock_column(:notes, :text, limit: 55),
mock_column(:notes, :text, limit: 55)
])
expect(AnnotateModels.get_schema_info(klass, 'Schema Info')).to eql(<<-EOS)
......@@ -91,7 +90,9 @@ EOS
end
it 'should get schema info even if the primary key is not set' do
klass = mock_class(:users, nil, [
klass = mock_class(:users,
nil,
[
mock_column(:id, :integer),
mock_column(:name, :string, limit: 50)
])
......@@ -108,7 +109,9 @@ EOS
end
it 'should get schema info even if the primary key is array, if using composite_primary_keys' do
klass = mock_class(:users, [:a_id, :b_id], [
klass = mock_class(:users,
[:a_id, :b_id],
[
mock_column(:a_id, :integer),
mock_column(:b_id, :integer),
mock_column(:name, :string, limit: 50)
......@@ -127,7 +130,9 @@ EOS
end
it 'should get schema info with enum type' do
klass = mock_class(:users, nil, [
klass = mock_class(:users,
nil,
[
mock_column(:id, :integer),
mock_column(:name, :enum, limit: [:enum1, :enum2])
])
......@@ -144,12 +149,14 @@ EOS
end
it 'should get schema info with unsigned' do
klass = mock_class(:users, nil, [
klass = mock_class(:users,
nil,
[
mock_column(:id, :integer),
mock_column(:integer, :integer, unsigned?: true),
mock_column(:bigint, :bigint, unsigned?: true),
mock_column(:float, :float, unsigned?: true),
mock_column(:decimal, :decimal, unsigned?: true, :precision => 10, :scale => 2),
mock_column(:decimal, :decimal, unsigned?: true, precision: 10, scale: 2),
])
expect(AnnotateModels.get_schema_info(klass, 'Schema Info')).to eql(<<-EOS)
......@@ -167,7 +174,9 @@ EOS
end
it 'should get schema info for integer and boolean with default' do
klass = mock_class(:users, :id, [
klass = mock_class(:users,
:id,
[
mock_column(:id, :integer),
mock_column(:size, :integer, default: 20),
mock_column(:flag, :boolean, default: false)
......@@ -185,26 +194,23 @@ EOS
end
it 'should get foreign key info' do
klass = mock_class(:users, :id, [
klass = mock_class(:users,
:id,
[
mock_column(:id, :integer),
mock_column(:foreign_thing_id, :integer),
], [],
mock_column(:foreign_thing_id, :integer)
],
[],
[
mock_foreign_key(
'fk_rails_cf2568e89e',
mock_foreign_key('fk_rails_cf2568e89e',
'foreign_thing_id',
'foreign_things'
),
mock_foreign_key(
'custom_fk_name',
'foreign_things'),
mock_foreign_key('custom_fk_name',
'other_thing_id',
'other_things'
),
mock_foreign_key(
'fk_rails_a70234b26c',
'other_things'),
mock_foreign_key('fk_rails_a70234b26c',
'third_thing_id',
'third_things'
)
'third_things')
])
expect(AnnotateModels.get_schema_info(klass, 'Schema Info', show_foreign_keys: true)).to eql(<<-EOS)
# Schema Info
......@@ -224,19 +230,20 @@ EOS
end
it 'should get foreign key info if on_delete/on_update options present' do
klass = mock_class(:users, :id, [
klass = mock_class(:users,
:id,
[
mock_column(:id, :integer),
mock_column(:foreign_thing_id, :integer),
], [],
mock_column(:foreign_thing_id, :integer)
],
[],
[
mock_foreign_key(
'fk_rails_02e851e3b7',
mock_foreign_key('fk_rails_02e851e3b7',
'foreign_thing_id',
'foreign_things',
'id',
on_delete: 'on_delete_value',
on_update: 'on_update_value'
)
on_update: 'on_update_value')
])
expect(AnnotateModels.get_schema_info(klass, 'Schema Info', show_foreign_keys: true)).to eql(<<-EOS)
# Schema Info
......@@ -254,9 +261,11 @@ EOS
end
it 'should get indexes keys' do
klass = mock_class(:users, :id, [
klass = mock_class(:users,
:id,
[
mock_column(:id, :integer),
mock_column(:foreign_thing_id, :integer),
mock_column(:foreign_thing_id, :integer)
], [mock_index('index_rails_02e851e3b7', ['id']),
mock_index('index_rails_02e851e3b8', ['foreign_thing_id'])])
expect(AnnotateModels.get_schema_info(klass, 'Schema Info', show_indexes: true)).to eql(<<-EOS)
......@@ -275,10 +284,31 @@ EOS
EOS
end
it 'should get simple indexes keys' do
klass = mock_class(:users,
:id,
[
mock_column(:id, :integer),
mock_column(:foreign_thing_id, :integer)
], [mock_index('index_rails_02e851e3b7', ['id']),
mock_index('index_rails_02e851e3b8', ['foreign_thing_id'])])
expect(AnnotateModels.get_schema_info(klass, 'Schema Info', simple_indexes: true)).to eql(<<-EOS)
# Schema Info
#
# Table name: users
#
# id :integer not null, primary key
# foreign_thing_id :integer not null
#
EOS
end
it 'should not crash getting indexes keys' do
klass = mock_class(:users, :id, [
klass = mock_class(:users,
:id,
[
mock_column(:id, :integer),
mock_column(:foreign_thing_id, :integer),
mock_column(:foreign_thing_id, :integer)
], [])
expect(AnnotateModels.get_schema_info(klass, 'Schema Info', show_indexes: true)).to eql(<<-EOS)
# Schema Info
......@@ -292,11 +322,13 @@ EOS
end
it 'should get schema info as RDoc' do
klass = mock_class(:users, :id, [
klass = mock_class(:users,
:id,
[
mock_column(:id, :integer),
mock_column(:name, :string, limit: 50)
])
expect(AnnotateModels.get_schema_info(klass, AnnotateModels::PREFIX, :format_rdoc => true)).to eql(<<-EOS)
expect(AnnotateModels.get_schema_info(klass, AnnotateModels::PREFIX, format_rdoc: true)).to eql(<<-EOS)
# #{AnnotateModels::PREFIX}
#
# Table name: users
......@@ -309,6 +341,94 @@ EOS
EOS
end
it 'should get schema info as Markdown' do
klass = mock_class(:users,
:id,
[
mock_column(:id, :integer),
mock_column(:name, :string, limit: 50)
])
expect(AnnotateModels.get_schema_info(klass, AnnotateModels::PREFIX, format_markdown: true)).to eql(<<-EOS)
# #{AnnotateModels::PREFIX}
#
# Table name: `users`
#
# ### Columns
#
# Name | Type | Attributes
# ----------- | ------------------ | ---------------------------
# **`id`** | `integer` | `not null, primary key`
# **`name`** | `string(50)` | `not null`
#
EOS
end
it 'should get schema info as Markdown with foreign keys' do
klass = mock_class(:users,
:id,
[
mock_column(:id, :integer),
mock_column(:foreign_thing_id, :integer)
],
[],
[
mock_foreign_key('fk_rails_02e851e3b7',
'foreign_thing_id',
'foreign_things',
'id',
on_delete: 'on_delete_value',
on_update: 'on_update_value')
])
expect(AnnotateModels.get_schema_info(klass, AnnotateModels::PREFIX, format_markdown: true, show_foreign_keys: true)).to eql(<<-EOS)
# #{AnnotateModels::PREFIX}
#
# Table name: `users`
#
# ### Columns
#
# Name | Type | Attributes
# ----------------------- | ------------------ | ---------------------------
# **`id`** | `integer` | `not null, primary key`
# **`foreign_thing_id`** | `integer` | `not null`
#
# ### Foreign Keys
#
# * `fk_rails_...` (_ON DELETE => on_delete_value ON UPDATE => on_update_value_):
# * **`foreign_thing_id => foreign_things.id`**
#
EOS
end
it 'should get schema info as Markdown with indexes' do
klass = mock_class(:users,
:id,
[
mock_column(:id, :integer),
mock_column(:name, :string, limit: 50)
], [mock_index('index_rails_02e851e3b7', ['id']),
mock_index('index_rails_02e851e3b8', ['foreign_thing_id'])])
expect(AnnotateModels.get_schema_info(klass, AnnotateModels::PREFIX, format_markdown: true, show_indexes: true)).to eql(<<-EOS)
# #{AnnotateModels::PREFIX}
#
# Table name: `users`
#
# ### Columns
#
# Name | Type | Attributes
# ----------- | ------------------ | ---------------------------
# **`id`** | `integer` | `not null, primary key`
# **`name`** | `string(50)` | `not null`
#
# ### Indexes
#
# * `index_rails_02e851e3b7`:
# * **`id`**
# * `index_rails_02e851e3b8`:
# * **`foreign_thing_id`**
#
EOS
end
describe '#get_schema_info with custom options' do
def self.when_called_with(options = {})
expected = options.delete(:returns)
......@@ -357,7 +477,8 @@ EOS
#
EOS
when_called_with hide_limit_column_types: 'integer,boolean,string,text', returns:
when_called_with hide_limit_column_types: 'integer,boolean,string,text',
returns:
<<-EOS.strip_heredoc
# Schema Info
#
......@@ -428,7 +549,8 @@ EOS
[:notes, :text, { limit: 55 }]
]
when_called_with classified_sort: 'yes', with_columns: mocked_columns_without_id, returns:
when_called_with classified_sort: 'yes',
with_columns: mocked_columns_without_id, returns:
<<-EOS.strip_heredoc
# Schema Info
#
......@@ -614,9 +736,9 @@ EOS
Kernel.load "#{path}.rb"
expect(Kernel).not_to receive(:require).with(path)
expect(capturing(:stderr) {
expect(capturing(:stderr) do
check_class_name 'loaded_class.rb', 'LoadedClass'
}).not_to include('warning: already initialized constant LoadedClass::CONSTANT')
end).not_to include('warning: already initialized constant LoadedClass::CONSTANT')
end
end
......@@ -738,7 +860,6 @@ end
end
describe '#resolve_filename' do
it 'should return the test path for a model' do
filename_template = 'test/unit/%MODEL_NAME%_test.rb'
model_name = 'example_model'
......@@ -774,7 +895,9 @@ class User < ActiveRecord::Base
end
EOS
@klass = mock_class(:users, :id, [
@klass = mock_class(:users,
:id,
[
mock_column(:id, :integer),
mock_column(:name, :string, limit: 50)
])
......@@ -782,14 +905,15 @@ end
Annotate.reset_options
end
def write_model file_name, file_content
def write_model(file_name, file_content)
fname = File.join(@model_dir, file_name)
FileUtils.mkdir_p(File.dirname(fname))
File.open(fname, 'wb') { |f| f.write file_content }
return fname, file_content
[fname, file_content]
end
def annotate_one_file options = {}
def annotate_one_file(options = {})
Annotate.set_defaults(options)
options = Annotate.setup_options(options)
AnnotateModels.annotate_one_file(@model_file_name, @schema_info, :position_in_class, options)
......@@ -813,7 +937,7 @@ end
"# frozen_string_literal: true\n# encoding: utf-8",
'# frozen_string_literal: true',
'#frozen_string_literal: false',
'# -*- frozen_string_literal : true -*-',
'# -*- frozen_string_literal : true -*-'
].each { |magic_comment| yield magic_comment }
end
......@@ -842,8 +966,7 @@ end
describe 'with existing annotation => :before' do
before do
annotate_one_file position: :before
another_schema_info = AnnotateModels.get_schema_info(mock_class(:users, :id, [mock_column(:id, :integer),]),
'== Schema Info')
another_schema_info = AnnotateModels.get_schema_info(mock_class(:users, :id, [mock_column(:id, :integer)]), '== Schema Info')
@schema_info = another_schema_info
end
......@@ -866,8 +989,7 @@ end
describe 'with existing annotation => :after' do
before do
annotate_one_file position: :after
another_schema_info = AnnotateModels.get_schema_info(mock_class(:users, :id, [mock_column(:id, :integer),]),
'== Schema Info')
another_schema_info = AnnotateModels.get_schema_info(mock_class(:users, :id, [mock_column(:id, :integer)]), '== Schema Info')
@schema_info = another_schema_info
end
......@@ -899,7 +1021,9 @@ class Foo::User < ActiveRecord::Base
end
EOS
klass = mock_class(:'foo_users', :id, [
klass = mock_class(:'foo_users',
:id,
[
mock_column(:id, :integer),
mock_column(:name, :string, limit: 50)
])
......@@ -939,21 +1063,21 @@ end
end
it 'displays an error message' do
expect(capturing(:stdout) {
AnnotateModels.do_annotations :model_dir => @model_dir, :is_rake => true
}).to include("Unable to annotate #{@model_dir}/user.rb: oops")
expect(capturing(:stdout) do
AnnotateModels.do_annotations model_dir: @model_dir, is_rake: true
end).to include("Unable to annotate #{@model_dir}/user.rb: oops")
end
it 'displays the full stack trace with --trace' do
expect(capturing(:stdout) {
AnnotateModels.do_annotations :model_dir => @model_dir, :trace => true, :is_rake => true
}).to include("/spec/annotate/annotate_models_spec.rb:")
expect(capturing(:stdout) do
AnnotateModels.do_annotations model_dir: @model_dir, trace: true, is_rake: true
end).to include('/spec/annotate/annotate_models_spec.rb:')
end
it 'omits the full stack trace without --trace' do
expect(capturing(:stdout) {
AnnotateModels.do_annotations :model_dir => @model_dir, :trace => false, :is_rake => true
}).not_to include("/spec/annotate/annotate_models_spec.rb:")
expect(capturing(:stdout) do
AnnotateModels.do_annotations model_dir: @model_dir, trace: false, is_rake: true
end).not_to include('/spec/annotate/annotate_models_spec.rb:')
end
end
......@@ -969,28 +1093,28 @@ end
end
it 'displays an error message' do
expect(capturing(:stdout) {
AnnotateModels.remove_annotations :model_dir => @model_dir, :is_rake => true
}).to include("Unable to deannotate #{@model_dir}/user.rb: oops")
expect(capturing(:stdout) do
AnnotateModels.remove_annotations model_dir: @model_dir, is_rake: true
end).to include("Unable to deannotate #{@model_dir}/user.rb: oops")
end
it 'displays the full stack trace' do
expect(capturing(:stdout) {
AnnotateModels.remove_annotations :model_dir => @model_dir, :trace => true, :is_rake => true
}).to include("/user.rb:2:in `<class:User>'")
expect(capturing(:stdout) do
AnnotateModels.remove_annotations model_dir: @model_dir, trace: true, is_rake: true
end).to include("/user.rb:2:in `<class:User>'")
end
it 'omits the full stack trace without --trace' do
expect(capturing(:stdout) {
AnnotateModels.remove_annotations :model_dir => @model_dir, :trace => false, :is_rake => true
}).not_to include("/user.rb:2:in `<class:User>'")
expect(capturing(:stdout) do
AnnotateModels.remove_annotations model_dir: @model_dir, trace: false, is_rake: true
end).not_to include("/user.rb:2:in `<class:User>'")
end
end
end
describe '.annotate_model_file' do
before do
class Foo < ActiveRecord::Base; end;
class Foo < ActiveRecord::Base; end
allow(AnnotateModels).to receive(:get_model_class).with('foo.rb') { Foo }
allow(Foo).to receive(:table_exists?) { false }
end
......
......@@ -2,10 +2,7 @@ module Annotate
module Validations
module Common
def self.test_commands
return %q{
bin/annotate &&
bin/annotate --routes
}
'bin/annotate && bin/annotate --routes'
end
def self.verify_output(output)
......@@ -13,49 +10,47 @@ module Annotate
output.should =~ /Route file annotated./
end
def self.verify_files(which_files, test_rig, schema_annotation, routes_annotation, place_before=true)
check_task_model(test_rig, schema_annotation, place_before) if(which_files[:model])
check_task_unittest(test_rig, schema_annotation, place_before) if(which_files[:test])
check_task_fixture(test_rig, schema_annotation, place_before) if(which_files[:fixture])
check_task_factory(test_rig, schema_annotation, place_before) if(which_files[:factory])
check_routes(test_rig, routes_annotation, place_before) if(which_files[:routes])
def self.verify_files(which_files, test_rig, schema_annotation, routes_annotation, place_before = true)
check_task_model(test_rig, schema_annotation, place_before) if which_files[:model]
check_task_unittest(test_rig, schema_annotation, place_before) if which_files[:test]
check_task_fixture(test_rig, schema_annotation, place_before) if which_files[:fixture]
check_task_factory(test_rig, schema_annotation, place_before) if which_files[:factory]
check_routes(test_rig, routes_annotation, place_before) if which_files[:routes]
end
def self.check_task_model(test_rig, annotation, place_before=true)
model = apply_annotation(test_rig, "app/models/task.rb", annotation, place_before)
File.read("app/models/task.rb").should == model
def self.check_task_model(test_rig, annotation, place_before = true)
model = apply_annotation(test_rig, 'app/models/task.rb', annotation, place_before)
File.read('app/models/task.rb').should == model
end
def self.check_routes(test_rig, annotation, place_before=true)
routes = apply_annotation(test_rig, "config/routes.rb", annotation, place_before)
File.read("config/routes.rb").
sub(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/, 'YYYY-MM-DD HH:MM').
should == routes
def self.check_routes(test_rig, annotation, place_before = true)
routes = apply_annotation(test_rig, 'config/routes.rb', annotation, place_before)
File.read('config/routes.rb')
.sub(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/, 'YYYY-MM-DD HH:MM')
.should == routes
end
def self.check_task_unittest(test_rig, annotation, place_before=true)
unittest = apply_annotation(test_rig, "test/unit/task_test.rb", annotation, place_before)
File.read("test/unit/task_test.rb").should == unittest
def self.check_task_unittest(test_rig, annotation, place_before = true)
unittest = apply_annotation(test_rig, 'test/unit/task_test.rb', annotation, place_before)
File.read('test/unit/task_test.rb').should == unittest
end
def self.check_task_modeltest(test_rig, annotation, place_before=true)
unittest = apply_annotation(test_rig, "test/models/task_test.rb", annotation, place_before)
File.read("test/models/task_test.rb").should == unittest
unittest = apply_annotation(test_rig, 'test/models/task_test.rb', annotation, place_before)
File.read('test/models/task_test.rb').should == unittest
end
def self.check_task_factory(test_rig, annotation, place_before=true)
fixture = apply_annotation(test_rig, "test/factories/tasks.rb", annotation, place_before)
File.read("test/factories/tasks.rb").should == fixture
fixture = apply_annotation(test_rig, 'test/factories/tasks.rb', annotation, place_before)
File.read('test/factories/tasks.rb').should == fixture
end
def self.check_task_fixture(test_rig, annotation, place_before=true)
fixture = apply_annotation(test_rig, "test/fixtures/tasks.yml", annotation, place_before)
File.read("test/fixtures/tasks.yml").should == fixture
def self.check_task_fixture(test_rig, annotation, place_before = true)
fixture = apply_annotation(test_rig, 'test/fixtures/tasks.yml', annotation, place_before)
File.read('test/fixtures/tasks.yml').should == fixture
end
protected
def self.apply_annotation(test_rig, fname, annotation, place_before=true)
def self.apply_annotation(test_rig, fname, annotation, place_before = true)
corpus = File.read(File.join(test_rig, fname))
if place_before
annotation + "\n" + corpus
......
......@@ -17,12 +17,13 @@ ENV['BUNDLE_GEMFILE'] = './Gemfile'
describe "annotate inside Rails, using #{CURRENT_RUBY}" do
chosen_scenario = nil
if !ENV['SCENARIO'].blank?
unless ENV['SCENARIO'].blank?
chosen_scenario = File.expand_path(ENV['SCENARIO'])
raise "Can't find specified scenario '#{chosen_scenario}'!" unless(File.directory?(chosen_scenario))
raise "Can't find specified scenario '#{chosen_scenario}'!" unless File.directory?(chosen_scenario)
end
Annotate::Integration::SCENARIOS.each do |test_rig, base_dir, test_name|
next if(chosen_scenario && chosen_scenario != test_rig)
next if chosen_scenario && chosen_scenario != test_rig
it "works under #{test_name}" do
unless USING_RVM
skip 'Must have RVM installed.'
......@@ -51,7 +52,7 @@ describe "annotate inside Rails, using #{CURRENT_RUBY}" do
# By default, rvm_ruby_string isn't inherited over properly, so let's
# make sure it's there so our .rvmrc will work.
ENV['rvm_ruby_string']=CURRENT_RUBY
ENV['rvm_ruby_string'] = CURRENT_RUBY
require base_dir.to_s # Will get "#{base_dir}.rb"...
klass = "Annotate::Validations::#{base_dir.tr('.', '_').classify}".constantize
......
......@@ -4,7 +4,7 @@ module Annotate
module Validations
class Rails328 < Base
def self.schema_annotation
return <<-RUBY
<<-RUBY
# == Schema Information
#
# Table name: tasks
......@@ -18,7 +18,7 @@ RUBY
end
def self.route_annotation
return <<-RUBY
<<-RUBY
# == Route Map (Updated YYYY-MM-DD HH:MM)
#
# tasks GET /tasks(.:format) tasks#index
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment