diff --git a/.travis.yml b/.travis.yml index 5771c6a..6c2e05e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,15 +7,9 @@ before_install: bundler_args: --without development rvm: - - 1.8.7 - - 1.9.2 - - 1.9.3 - - 2.0.0 - - 2.2.1 -# - ruby-head # The latest Ruby, whatever version it happens to be. -# - jruby-18mode -# - jruby-19mode - + - 2.2.9 + - 2.3.6 + - 2.4.3 matrix: allow_failures: @@ -23,8 +17,8 @@ matrix: include: - rvm: rbx gemfile: gemfiles/Gemfile.rbx - - rvm: 2.1.5 - env: COVERAGE=true + # - rvm: 2.4.3 # + # env: COVERAGE=true # exclude: - rvm: rbx gemfile: Gemfile diff --git a/Gemfile b/Gemfile index 242ade7..fb18e44 100644 --- a/Gemfile +++ b/Gemfile @@ -4,10 +4,10 @@ source 'https://rubygems.org' gemspec group :development, :test do - gem "rake", "~> 10.4" - gem "test-unit", "~> 3.0" - gem "coveralls", ">= 0.7", :require => false, :platforms => :mri_21 - gem "rspec", ">= 3.4" + gem 'rake', '~> 10.4' + gem 'test-unit', '~> 3.0' + gem 'coveralls', '>= 0.7', :require => false, :platforms => :mri_21 + gem 'rspec', '>= 3.4' end # Local Variables: diff --git a/Gemfile.lock b/Gemfile.lock index 63ce07d..00eac8e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,83 +1,68 @@ PATH remote: . specs: - rubytree (0.9.7) - json (~> 1.8) - structured_warnings (~> 0.2) + rubytree (1.0.0) + json (~> 2.1) + structured_warnings (~> 0.3) GEM remote: https://rubygems.org/ specs: - coveralls (0.8.10) - json (~> 1.8) - rest-client (>= 1.6.8, < 2) - simplecov (~> 0.11.0) + coveralls (0.8.21) + json (>= 1.8, < 3) + simplecov (~> 0.14.1) term-ansicolor (~> 1.3) - thor (~> 0.19.1) - tins (~> 1.6.0) - diff-lcs (1.2.5) + thor (~> 0.19.4) + tins (~> 1.6) + diff-lcs (1.3) docile (1.1.5) - domain_name (0.5.25) - unf (>= 0.0.5, < 1.0.0) - http-cookie (1.0.2) - domain_name (~> 0.5) - json (1.8.3) - mime-types (2.99) - netrc (0.11.0) - power_assert (0.2.6) - rake (10.4.2) - rdoc (4.2.1) - json (~> 1.4) - rest-client (1.8.0) - http-cookie (>= 1.0.2, < 2.0) - mime-types (>= 1.16, < 3.0) - netrc (~> 0.7) - rspec (3.4.0) - rspec-core (~> 3.4.0) - rspec-expectations (~> 3.4.0) - rspec-mocks (~> 3.4.0) - rspec-core (3.4.1) - rspec-support (~> 3.4.0) - rspec-expectations (3.4.0) + json (2.1.0) + power_assert (1.1.1) + rake (10.5.0) + rdoc (6.0.0) + rspec (3.7.0) + rspec-core (~> 3.7.0) + rspec-expectations (~> 3.7.0) + rspec-mocks (~> 3.7.0) + rspec-core (3.7.0) + rspec-support (~> 3.7.0) + rspec-expectations (3.7.0) diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.4.0) - rspec-mocks (3.4.0) + rspec-support (~> 3.7.0) + rspec-mocks (3.7.0) diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.4.0) - rspec-support (3.4.1) + rspec-support (~> 3.7.0) + rspec-support (3.7.0) rtags (0.97) rtagstask (0.0.4) rtags (> 0.0.0) - simplecov (0.11.1) + simplecov (0.14.1) docile (~> 1.1.0) - json (~> 1.8) + json (>= 1.8, < 3) simplecov-html (~> 0.10.0) - simplecov-html (0.10.0) - structured_warnings (0.2.0) - term-ansicolor (1.3.2) + simplecov-html (0.10.2) + structured_warnings (0.3.0) + term-ansicolor (1.6.0) tins (~> 1.0) - test-unit (3.1.5) + test-unit (3.2.7) power_assert - thor (0.19.1) - tins (1.6.0) - unf (0.1.4) - unf_ext - unf_ext (0.0.7.1) - yard (0.8.7.6) + thor (0.19.4) + tins (1.16.3) + yard (0.9.12) PLATFORMS ruby DEPENDENCIES - bundler (~> 1.7) + bundler (~> 1.16) coveralls (>= 0.7) rake (~> 10.4) - rdoc (~> 4.2) + rdoc (~> 6.0) rspec (>= 3.4) rtagstask (~> 0.0) rubytree! test-unit (~> 3.0) - yard (~> 0.8) + yard (~> 0.9) BUNDLED WITH - 1.10.2 + 1.16.0 diff --git a/README.md b/README.md index f86df18..aa1da31 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # **RubyTree** # @@ -120,7 +120,7 @@ This example can also be found at ## REQUIREMENTS: ## -* [Ruby][] 1.8.x, 1.9.x, 2.0.x, or 2.1.x. +* [Ruby][] 2.2.x, 2.3.x or 2.4.x * Run-time Dependencies: @@ -244,8 +244,8 @@ A big thanks to the following contributors for helping improve **RubyTree**: [BSD]: http://opensource.org/licenses/bsd-license.php "BSD License" [Binary tree]: http://en.wikipedia.org/wiki/Binary_tree "Binary Tree Data Structure" [Bundler]: http://bundler.io "Bundler" -[Comparable]: http://ruby-doc.org/core-1.8.7/Comparable.html "Comparable mix-in" -[Enumerable]: http://ruby-doc.org/core-1.9.3/Enumerable.html "Enumerable mix-in" +[Comparable]: http://ruby-doc.org/core-2.4.2/Comparable.html "Comparable mix-in" +[Enumerable]: http://ruby-doc.org/core-2.4.2/Enumerable.html "Enumerable mix-in" [JSON]: http://flori.github.com/json "JSON" [Rake]: https://rubygems.org/gems/rake "Rake" [Ruby]: http://www.ruby-lang.org "Ruby Programming Language" @@ -254,7 +254,7 @@ A big thanks to the following contributors for helping improve **RubyTree**: [breadth-first]: http://en.wikipedia.org/wiki/Breadth-first_search "Breadth-first (level-first) Traversal" [git]: http://git-scm.com "Git SCM" [in-order]: http://en.wikipedia.org/wiki/Tree_traversal#In-order "In-order (symmetric) Traversal" -[marshaling]: http://ruby-doc.org/core-1.8.7/Marshal.html "Marshaling in Ruby" +[marshaling]: http://ruby-doc.org/core-2.4.2/Marshal.html "Marshaling in Ruby" [post-order]: http://en.wikipedia.org/wiki/Tree_traversal#Post-order "Post-ordered Traversal" [pre-order]: http://en.wikipedia.org/wiki/Tree_traversal#Pre-order "Pre-ordered Traversal" [rt@github]: http://github.com/evolve75/RubyTree "RubyTree Project Page on Github" diff --git a/Rakefile b/Rakefile index 01e4019..efc0af5 100644 --- a/Rakefile +++ b/Rakefile @@ -33,23 +33,23 @@ # require 'rubygems' -GEM_SPEC = eval(File.read("rubytree.gemspec")) # Load the gemspec. +GEM_SPEC = eval(File.read('./rubytree.gemspec')) # Load the gemspec. PKG_NAME = GEM_SPEC.name PKG_VER = GEM_SPEC.version GEM_NAME = "#{PKG_NAME}-#{PKG_VER}.gem" -desc "Default Task (Run the tests)" +desc 'Default Task (Run the tests)' task :default do - if ENV["COVERAGE"] - Rake::Task["test:coverage"].invoke + if ENV['COVERAGE'] + Rake::Task['test:coverage'].invoke else - Rake::Task["test:unit"].invoke - Rake::Task["spec"].invoke + Rake::Task['test:unit'].invoke + Rake::Task['spec'].invoke end end -desc "Display the current gem version" +desc 'Display the current gem version' task :version do puts "Current Version: #{GEM_NAME}" end @@ -59,21 +59,21 @@ task :clean => 'gem:clobber_package' CLEAN.include('coverage') task :clobber => [:clean, 'doc:clobber_rdoc', 'doc:clobber_yard'] -desc "Open an irb session preloaded with this library" +desc 'Open an irb session preloaded with this library' task :console do - sh "irb -rubygems -r ./lib/tree.rb" + sh 'irb -rubygems -r ./lib/tree.rb' end namespace :doc do # ................................ Documentation begin - gem 'rdoc', ">= 2.4.2" # To get around a stupid bug in Ruby 1.9.2 Rake. + gem 'rdoc', '>= 2.4.2' # To get around a stupid bug in Ruby 1.9.2 Rake. require 'rdoc/task' Rake::RDocTask.new do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = "#{PKG_NAME}-#{PKG_VER}" rdoc.main = 'README.rdoc' rdoc.rdoc_files.include(GEM_SPEC.extra_rdoc_files) - rdoc.rdoc_files.include('lib/**/*.rb') + rdoc.rdoc_files.include('./lib/**/*.rb') end rescue LoadError # Oh well. @@ -83,19 +83,19 @@ namespace :doc do # ................................ Documentation require 'yard' YARD::Rake::YardocTask.new do |t| t.files = ['lib/**/*.rb', '-', GEM_SPEC.extra_rdoc_files] - t.options = ['--no-private', '--embed-mixins'] + t.options = %w(--no-private --embed-mixins) end rescue LoadError # Oh well. end - desc "Remove YARD Documentation" + desc 'Remove YARD Documentation' task :clobber_yard do rm_rf 'doc' end end -desc "Run the test cases" +desc 'Run the test cases' task :test => 'test:unit' namespace :test do # ................................ Test related @@ -107,7 +107,7 @@ namespace :test do # ................................ Test related test.verbose = false end - desc "Run the examples" + desc 'Run the examples' Rake::TestTask.new(:examples) do |example| example.libs << 'lib' << 'examples' example.pattern = 'examples/**/example_*.rb' @@ -115,7 +115,7 @@ namespace :test do # ................................ Test related example.warning = false end - desc "Run the code coverage" + desc 'Run the code coverage' task :coverage do ruby 'test/run_test.rb' end @@ -123,7 +123,7 @@ namespace :test do # ................................ Test related begin require 'rcov/rcovtask' Rcov::RcovTask.new(:rcov) do |t| - t.libs << "test" + t.libs << 'test' t.test_files = FileList['test/**/test_*.rb'] t.verbose = true t.rcov_opts << '--exclude /gems/,/Library/,/usr/,spec,lib/tasks' @@ -139,7 +139,7 @@ begin # ................................ rspec tests RSpec::Core::RakeTask.new(:spec) do |t| t.fail_on_error = false - t.rspec_opts = ["--color", "--format doc"] + t.rspec_opts = ['--color', '--format doc'] end rescue LoadError # Cannot load rspec. @@ -164,7 +164,7 @@ namespace :gem do # ................................ Gem related pkg.need_tar = true end - desc "Push the gem into the Rubygems repository" + desc 'Push the gem into the Rubygems repository' task :push => :gem do sh "gem push pkg/#{GEM_NAME}" end diff --git a/examples/example_basic.rb b/examples/example_basic.rb index f30aa32..48ee6de 100755 --- a/examples/example_basic.rb +++ b/examples/example_basic.rb @@ -26,19 +26,19 @@ require 'tree' # Load the library # ..... Create the root node first. Note that every node has a name and an optional content payload. -root_node = Tree::TreeNode.new("ROOT", "Root Content") +root_node = Tree::TreeNode.new('ROOT', 'Root Content') root_node.print_tree # ..... Now insert the child nodes. Note that you can "chain" the child insertions for a given path to any depth. -root_node << Tree::TreeNode.new("CHILD1", "Child1 Content") << Tree::TreeNode.new("GRANDCHILD1", "GrandChild1 Content") -root_node << Tree::TreeNode.new("CHILD2", "Child2 Content") +root_node << Tree::TreeNode.new('CHILD1', 'Child1 Content') << Tree::TreeNode.new('GRANDCHILD1', 'GrandChild1 Content') +root_node << Tree::TreeNode.new('CHILD2', 'Child2 Content') # ..... Lets print the representation to stdout. This is primarily used for debugging purposes. root_node.print_tree # ..... Lets directly access children and grandchildren of the root. The can be "chained" for a given path to any depth. -child1 = root_node["CHILD1"] -grand_child1 = root_node["CHILD1"]["GRANDCHILD1"] +child1 = root_node['CHILD1'] +grand_child1 = root_node['CHILD1']['GRANDCHILD1'] # ..... Now lets retrieve siblings of the current node as an array. siblings_of_child1 = child1.siblings diff --git a/lib/rubytree.rb b/lib/rubytree.rb index f9a9c61..bd05d97 100644 --- a/lib/rubytree.rb +++ b/lib/rubytree.rb @@ -38,4 +38,4 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -require "tree.rb" +require 'tree.rb' diff --git a/lib/tree.rb b/lib/tree.rb index 90b97af..c20b890 100644 --- a/lib/tree.rb +++ b/lib/tree.rb @@ -9,7 +9,7 @@ # Author:: Anupam Sengupta (anupamsg@gmail.com) # -# Copyright (c) 2006-2015 Anupam Sengupta +# Copyright (c) 2006-2015, 2017 Anupam Sengupta # # All rights reserved. # @@ -83,6 +83,7 @@ module Tree # {include:file:examples/example_basic.rb} # # @author Anupam Sengupta + # noinspection RubyTooManyMethodsInspection class TreeNode include Enumerable include Comparable @@ -132,7 +133,7 @@ class TreeNode # @return [Tree::TreeNode] Root of the (sub)tree. def root root = self - root = root.parent while !root.is_root? + root = root.parent until root.is_root? root end @@ -177,7 +178,7 @@ def parentage parentage_array = [] prev_parent = self.parent - while (prev_parent) + while prev_parent parentage_array << prev_parent prev_parent = prev_parent.parent end @@ -215,13 +216,13 @@ def has_children? # # @see #[] def initialize(name, content = nil) - raise ArgumentError, "Node name HAS to be provided!" if name == nil + raise ArgumentError, 'Node name HAS to be provided!' if name == nil @name, @content = name, content if name.kind_of?(Integer) - warn StandardWarning, - "Using integer as node name."\ - " Semantics of TreeNode[] may not be what you expect!"\ + warn StructuredWarnings::StandardWarning, + 'Using integer as node name.'\ + ' Semantics of TreeNode[] may not be what you expect!'\ " #{name} #{content}" end @@ -256,7 +257,7 @@ def detached_subtree_copy alias :dup :detached_subtree_copy # Returns a {marshal-dump}[http://ruby-doc.org/core-1.8.7/Marshal.html] - # represention of the (sub)tree rooted at this node. + # representation of the (sub)tree rooted at this node. # def marshal_dump self.collect { |node| node.create_dump_rep } @@ -265,15 +266,15 @@ def marshal_dump # Creates a dump representation of this node and returns the same as # a hash. def create_dump_rep # :nodoc: - { :name => @name, - :parent => (is_root? ? nil : @parent.name), - :content => Marshal.dump(@content) + {name: @name, + parent: (is_root? ? nil : @parent.name), + content: Marshal.dump(@content) } end protected :create_dump_rep - # Loads a marshalled dump of a tree and returns the root node of the + # Loads a marshaled dump of a tree and returns the root node of the # reconstructed tree. See the # {Marshal}[http://ruby-doc.org/core-1.8.7/Marshal.html] class for # additional details. @@ -289,7 +290,7 @@ def marshal_load(dumped_tree_array) parent_name = node_hash[:parent] content = Marshal.load(node_hash[:content]) - if parent_name then + if parent_name nodes[name] = current_node = Tree::TreeNode.new(name, content) nodes[parent_name].add current_node else @@ -308,11 +309,7 @@ def marshal_load(dumped_tree_array) # # @return [String] A string representation of the node. def to_s - "Node Name: #{@name}" + - " Content: " + (@content.to_s || "") + - " Parent: " + (is_root?() ? "" : @parent.name.to_s) + - " Children: #{@children.length}" + - " Total Nodes: #{size()}" + "Node Name: #{@name} Content: #{(@content.to_s || '')} Parent: #{(is_root? ? '' : @parent.name.to_s)} Children: #{@children.length} Total Nodes: #{size}" end # @!group Structure Modification @@ -354,7 +351,7 @@ def <<(child) # # -children.size..children.size # - # This is to prevent +nil+ nodes being created as children if a non-existant + # This is to prevent +nil+ nodes being created as children if a non-existent # position is used. # # If the new node being added has an existing parent node, then it will be @@ -381,11 +378,11 @@ def <<(child) def add(child, at_index = -1) # Only handles the immediate child scenario raise ArgumentError, - "Attempting to add a nil node" unless child + 'Attempting to add a nil node' unless child raise ArgumentError, - "Attempting add node to itself" if self.equal?(child) + 'Attempting add node to itself' if self.equal?(child) raise ArgumentError, - "Attempting add root as a child" if child.equal?(root) + 'Attempting add root as a child' if child.equal?(root) # Lazy mans unique test, won't test if children of child are unique in # this tree too. @@ -397,15 +394,15 @@ def add(child, at_index = -1) if insertion_range.include?(at_index) @children.insert(at_index, child) else - raise "Attempting to insert a child at a non-existent location"\ + raise 'Attempting to insert a child at a non-existent location'\ " (#{at_index}) "\ - "when only positions from "\ + 'when only positions from '\ "#{insertion_range.min} to #{insertion_range.max} exist." end @children_hash[child.name] = child child.parent = self - return child + child end # Return a range of valid insertion positions. Used in the #add method. @@ -472,7 +469,7 @@ def replace!(old_child, new_child) old_child = remove! old_child add new_child, child_index - return old_child + old_child end # Replaces the node with another node @@ -605,14 +602,14 @@ def freeze_tree! # @see #initialize def [](name_or_index, num_as_name=false) raise ArgumentError, - "Name_or_index needs to be provided!" if name_or_index == nil + 'Name_or_index needs to be provided!' if name_or_index == nil if name_or_index.kind_of?(Integer) and not num_as_name @children[name_or_index] else if num_as_name and not name_or_index.kind_of?(Integer) - warn StandardWarning, - "Redundant use of the `num_as_name` flag for non-integer node name" + warn StructuredWarnings::StandardWarning, + 'Redundant use of the `num_as_name` flag for non-integer node name' end @children_hash[name_or_index] end @@ -624,6 +621,7 @@ def [](name_or_index, num_as_name=false) # The traversal is *depth-first* and from *left-to-right* in pre-ordered # sequence. # + # @param [Object] block # @yieldparam node [Tree::TreeNode] Each node. # # @see #preordered_each @@ -631,6 +629,7 @@ def [](name_or_index, num_as_name=false) # # @return [Tree::TreeNode] this node, if a block if given # @return [Enumerator] an enumerator on this tree, if a block is *not* given + # noinspection RubyUnusedLocalVariable def each(&block) # :yields: node return self.to_enum unless block_given? @@ -646,7 +645,7 @@ def each(&block) # :yields: node end end - return self if block_given? + self if block_given? end # Traverses the (sub)tree rooted at this node in pre-ordered sequence. @@ -665,20 +664,22 @@ def preordered_each(&block) # :yields: node # Traverses the (sub)tree rooted at this node in post-ordered sequence. # + # @param [Object] block # @yieldparam node [Tree::TreeNode] Each node. # # @see #preordered_each # @see #breadth_each # @return [Tree::TreeNode] this node, if a block if given # @return [Enumerator] an enumerator on this tree, if a block is *not* given + # noinspection RubyUnusedLocalVariable def postordered_each(&block) return self.to_enum(:postordered_each) unless block_given? # Using a marked node in order to skip adding the children of nodes that # have already been visited. This allows the stack depth to be controlled, # and also allows stateful backtracking. - markednode = Struct.new(:node, :visited) - node_stack = [markednode.new(self, false)] # Start with self + marked_node = Struct.new(:node, :visited) + node_stack = [marked_node.new(self, false)] # Start with self until node_stack.empty? peek_node = node_stack[0] @@ -686,7 +687,7 @@ def postordered_each(&block) peek_node.visited = true # Add the children to the stack. Use the marking structure. marked_children = - peek_node.node.children.map {|node| markednode.new(node, false)} + peek_node.node.children.map {|node| marked_node.new(node, false)} node_stack = marked_children.concat(node_stack) next else @@ -694,13 +695,14 @@ def postordered_each(&block) end end - return self if block_given? + self if block_given? end # Performs breadth-first traversal of the (sub)tree rooted at this node. The # traversal at a given level is from *left-to-right*. this node itself is # the first node to be traversed. # + # @param [Object] block # @yieldparam node [Tree::TreeNode] Each node. # # @see #preordered_each @@ -708,6 +710,7 @@ def postordered_each(&block) # # @return [Tree::TreeNode] this node, if a block if given # @return [Enumerator] an enumerator on this tree, if a block is *not* given + # noinspection RubyUnusedLocalVariable def breadth_each(&block) return self.to_enum(:breadth_each) unless block_given? @@ -721,7 +724,7 @@ def breadth_each(&block) node_to_traverse.children { |child| node_queue.push child } end - return self if block_given? + self if block_given? end # An array of all the immediate children of this node. The child @@ -739,9 +742,9 @@ def breadth_each(&block) def children if block_given? @children.each {|child| yield child} - return self + self else - return @children.clone + @children.clone end end @@ -751,6 +754,7 @@ def children # May yield this node as well if this is a leaf node. # Leaf traversal is *depth-first* and *left-to-right*. # + # @param [Object] block # @yieldparam node [Tree::TreeNode] Each leaf node. # # @see #each @@ -758,12 +762,13 @@ def children # # @return [Tree::TreeNode] this node, if a block if given # @return [Array] An array of the leaf nodes - def each_leaf &block + # noinspection RubyUnusedLocalVariable + def each_leaf(&block) if block_given? self.each { |node| yield(node) if node.is_leaf? } - return self + self else - self.select { |node| node.is_leaf?} + self.select { |node| node.is_leaf? } end end @@ -776,7 +781,7 @@ def each_leaf &block # # @return [Tree::TreeNode] The first child, or +nil+ if none is present. def first_child - children.first + @children.first end # Last child of this node. @@ -784,7 +789,7 @@ def first_child # # @return [Tree::TreeNode] The last child, or +nil+ if none is present. def last_child - children.last + @children.last end # @!group Navigating the Sibling Nodes @@ -858,7 +863,7 @@ def is_last_sibling? def siblings if block_given? parent.children.each { |sibling| yield sibling if sibling != self } - return self + self else return [] if is_root? siblings = [] @@ -892,8 +897,8 @@ def is_only_child? def next_sibling return nil if is_root? - myidx = parent.children.index(self) - parent.children.at(myidx + 1) if myidx + idx = parent.children.index(self) + parent.children.at(idx + 1) if idx end # Previous sibling of this node. @@ -909,15 +914,15 @@ def next_sibling def previous_sibling return nil if is_root? - myidx = parent.children.index(self) - parent.children.at(myidx - 1) if myidx && myidx > 0 + idx = parent.children.index(self) + parent.children.at(idx - 1) if idx && idx > 0 end # @!endgroup - # Provides a comparision operation for the nodes. + # Provides a comparison operation for the nodes. # - # Comparision is based on the natural ordering of the node name objects. + # Comparison is based on the natural ordering of the node name objects. # # @param [Tree::TreeNode] other The other node to compare against. # @@ -935,7 +940,7 @@ def <=>(other) # @param [Integer] max_depth optional maximum depth at which the printing # with stop. # @param [Proc] block optional block to use for rendering - def print_tree(level = node_depth, max_depth = nil, + def print_tree(level = self.node_depth, max_depth = nil, block = lambda { |node, prefix| puts "#{prefix} #{node.name}" }) prefix = '' diff --git a/lib/tree/binarytree.rb b/lib/tree/binarytree.rb index 1aaf3a8..8a04d85 100644 --- a/lib/tree/binarytree.rb +++ b/lib/tree/binarytree.rb @@ -38,7 +38,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -require 'tree' +require_relative '../tree' module Tree @@ -114,7 +114,7 @@ def is_right_child? # @raise [ArgumentError] This exception is raised if two children are # already present. def add(child) - raise ArgumentError, "Already has two child nodes" if @children.size == 2 + raise ArgumentError, 'Already has two child nodes' if @children.size == 2 super(child) end @@ -150,12 +150,12 @@ def add(child) # @raise [ArgumentError] This exception is raised if a non-hash is passed. # @return [Array] Array of child nodes added def add_from_hash(hashed_subtree) - raise ArgumentError, "Too many children"\ + raise ArgumentError, 'Too many children'\ if hashed_subtree.size + @children.size > 2 super(hashed_subtree) end - # Performs inorder traversal (including this node). + # Performs in-order traversal (including this node). # # @yieldparam node [Tree::BinaryTreeNode] Each node (in-order). # @@ -164,9 +164,12 @@ def add_from_hash(hashed_subtree) # # @since 0.9.0 # + # @param [Object] block + # # @see #each # @see #preordered_each # @see #postordered_each + # noinspection RubyUnusedLocalVariable def inordered_each(&block) return self.to_enum unless block_given? @@ -179,13 +182,13 @@ def inordered_each(&block) node_stack.push(current_node) current_node = current_node.left_child else - current_node = node_stack.pop() + current_node = node_stack.pop yield current_node current_node = current_node.right_child end end - return self if block_given? + self if block_given? end @@ -201,7 +204,7 @@ def inordered_each(&block) # # @raise [ArgumentError] If the index is out of limits. def set_child_at(child, at_index) - raise ArgumentError "A binary tree cannot have more than two children."\ + raise ArgumentError 'A binary tree cannot have more than two children.'\ unless (0..1).include? at_index @children[at_index] = child diff --git a/lib/tree/tree_deps.rb b/lib/tree/tree_deps.rb index b417f79..8f05d8e 100644 --- a/lib/tree/tree_deps.rb +++ b/lib/tree/tree_deps.rb @@ -2,7 +2,7 @@ # # = rubytree_deps.rb - Dependencies for RubyTree # -# Centralizes and lists the dependencies forthe RubyTree gem. +# Centralizes and lists the dependencies for the RubyTree gem. # # Author:: Anupam Sengupta (anupamsg@gmail.com) # @@ -40,10 +40,10 @@ require 'structured_warnings' require 'json' -require 'tree/version' -require 'tree/utils/metrics_methods' -require 'tree/utils/path_methods' -require 'tree/utils/camel_case_method_handler' -require 'tree/utils/json_converter' -require 'tree/utils/tree_merge_handler' -require 'tree/utils/hash_converter' +require_relative '../tree/version' +require_relative '../tree/utils/metrics_methods' +require_relative '../tree/utils/path_methods' +require_relative '../tree/utils/camel_case_method_handler' +require_relative '../tree/utils/json_converter' +require_relative '../tree/utils/tree_merge_handler' +require_relative '../tree/utils/hash_converter' diff --git a/lib/tree/utils/camel_case_method_handler.rb b/lib/tree/utils/camel_case_method_handler.rb index 9f06896..5bce2e4 100644 --- a/lib/tree/utils/camel_case_method_handler.rb +++ b/lib/tree/utils/camel_case_method_handler.rb @@ -4,9 +4,9 @@ # # Author:: Anupam Sengupta (anupamsg@gmail.com) # -# Time-stamp: <2015-05-30 14:14:09 anupam> +# Time-stamp: <2017-12-21 13:42:15 anupam> # -# Copyright (C) 2012, 2013, 2015 Anupam Sengupta +# Copyright (C) 2012, 2013, 2015, 2017 Anupam Sengupta # # All rights reserved. # @@ -36,6 +36,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # +require_relative '../../../lib/tree' require 'structured_warnings' module Tree::Utils @@ -47,17 +48,17 @@ def self.included(base) # Allow the deprecated CamelCase method names. Display a warning. # :nodoc: def method_missing(meth, *args, &blk) - if self.respond_to?(new_method_name = to_snake_case(meth)) - warn DeprecatedMethodWarning, - "The camelCased methods are deprecated. "\ + if self.respond_to?((new_method_name = to_snake_case(meth))) + warn StructuredWarnings::DeprecatedMethodWarning, + 'The camelCased methods are deprecated. ' + "Please use #{new_method_name} instead of #{meth}" - return send(new_method_name, *args, &blk) + send(new_method_name, *args, &blk) else super end end - private + protected # @!visibility private # Convert a CamelCasedWord to a underscore separated camel_cased_word. @@ -65,11 +66,11 @@ def method_missing(meth, *args, &blk) # @param [String] camel_cased_word The word to be converted to snake_case. # @return [String] the snake_cased_word. def to_snake_case(camel_cased_word) - word = camel_cased_word.to_s.dup + word = camel_cased_word.to_s word.gsub!(/::/, '/') word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2') word.gsub!(/([a-z\d])([A-Z])/,'\1_\2') - word.tr!("-", "_") + word.tr!('-', '_') word.downcase! word end diff --git a/lib/tree/utils/hash_converter.rb b/lib/tree/utils/hash_converter.rb index ac71093..4b0b750 100644 --- a/lib/tree/utils/hash_converter.rb +++ b/lib/tree/utils/hash_converter.rb @@ -37,6 +37,8 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +require_relative '../../../lib/tree/utils/utils' + module Tree::Utils::HashConverter def self.included(base) @@ -92,16 +94,16 @@ module ClassMethods # values that are not hashes or nils. def from_hash(hash) - raise ArgumentError, "Argument must be a type of hash"\ + raise ArgumentError, 'Argument must be a type of hash'\ unless hash.is_a?(Hash) - raise ArgumentError, "Hash must have one top-level element"\ + raise ArgumentError, 'Hash must have one top-level element'\ if hash.size != 1 root, children = hash.first unless [Hash, NilClass].include?(children.class) - raise ArgumentError, "Invalid child. Must be nil or hash." + raise ArgumentError, 'Invalid child. Must be nil or hash.' end node = self.new(*root) @@ -138,7 +140,7 @@ def from_hash(hash) # @return [Array] Array of child nodes added # @see ClassMethods#from_hash def add_from_hash(children) - raise ArgumentError, "Argument must be a type of hash"\ + raise ArgumentError, 'Argument must be a type of hash'\ unless children.is_a?(Hash) child_nodes = [] diff --git a/lib/tree/utils/json_converter.rb b/lib/tree/utils/json_converter.rb index 4e0dd25..8ff173a 100644 --- a/lib/tree/utils/json_converter.rb +++ b/lib/tree/utils/json_converter.rb @@ -35,6 +35,7 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +require_relative '../utils/utils' require 'json' # Provides utility methods to convert a {Tree::TreeNode} to and from @@ -57,21 +58,24 @@ def self.included(base) # Rails uses JSON in ActiveSupport, and all Rails JSON encoding goes through # +as_json+. # + # @param [Object] options + # # @see #to_json # @see http://stackoverflow.com/a/6880638/273808 + # noinspection RubyUnusedLocalVariable def as_json(options = {}) json_hash = { - "name" => name, - "content" => content, - JSON.create_id => self.class.name + name: name, + content: content, + JSON.create_id => self.class.name } if has_children? - json_hash["children"] = children + json_hash['children'] = children end - return json_hash + json_hash end @@ -114,13 +118,13 @@ module ClassMethods # @see http://flori.github.com/json def json_create(json_hash) - node = new(json_hash["name"], json_hash["content"]) + node = new(json_hash['name'], json_hash['content']) - json_hash["children"].each do |child| + json_hash['children'].each do |child| node << child - end if json_hash["children"] + end if json_hash['children'] - return node + node end end diff --git a/lib/tree/utils/metrics_methods.rb b/lib/tree/utils/metrics_methods.rb index 4ccdac1..f246e4f 100644 --- a/lib/tree/utils/metrics_methods.rb +++ b/lib/tree/utils/metrics_methods.rb @@ -4,9 +4,9 @@ # # Author:: Anupam Sengupta (anupamsg@gmail.com) # -# Time-stamp: <2015-05-30 14:23:23 anupam> +# Time-stamp: <2017-12-21 12:49:25 anupam> # -# Copyright (C) 2013, 2015 Anupam Sengupta +# Copyright (C) 2013, 2015, 2017 Anupam Sengupta # # All rights reserved. # @@ -36,11 +36,13 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # +require_relative '../../../lib/tree' require 'structured_warnings' module Tree::Utils # Provides utility functions to measure various tree metrics. module TreeMetricsHandler + # noinspection RubyUnusedLocalVariable def self.included(base) # @!group Metrics and Measures @@ -66,7 +68,7 @@ def size # @return [Integer] The total number of nodes in this (sub)tree. # @see #size def length - size() + self.size end # @!attribute [r] node_height @@ -127,9 +129,9 @@ def level # # @see #node_depth def depth - warn DeprecatedMethodWarning, - "This method is deprecated. "\ - "Please use node_depth() or node_height() instead (bug # 22535)" + warn StructuredWarnings::DeprecatedMethodWarning, + 'This method is deprecated. '\ + 'Please use node_depth() or node_height() instead (bug # 22535)' return 1 if is_leaf? 1 + @children.collect { |child| child.depth }.max diff --git a/lib/tree/utils/path_methods.rb b/lib/tree/utils/path_methods.rb index 627aed9..b050221 100644 --- a/lib/tree/utils/path_methods.rb +++ b/lib/tree/utils/path_methods.rb @@ -36,9 +36,12 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # +require_relative '../../../lib/tree' + module Tree::Utils # Provides utility methods for path extraction module TreePathHandler + # noinspection RubyUnusedLocalVariable def self.included(base) # @!group Node Path @@ -53,7 +56,7 @@ def self.included(base) # @return [String] The node path with names separated using the specified # separator. def path_as_string(separator = '=>') - path_as_array().join(separator) + path_as_array.join(separator) end # Returns the node-names from this node to the root as an array. The first @@ -61,8 +64,8 @@ def path_as_string(separator = '=>') # # @return [Array] The array containing the node names for the path to this # node - def path_as_array() - get_path_name_array().reverse + def path_as_array + get_path_name_array.reverse end # @!visibility private @@ -76,10 +79,9 @@ def get_path_name_array(current_array_path = []) path_array = current_array_path + [name] if !parent # If detached node or root node. - return path_array + path_array else # Else recurse to parent node. path_array = parent.get_path_name_array(path_array) - return path_array end end diff --git a/lib/tree/utils/tree_merge_handler.rb b/lib/tree/utils/tree_merge_handler.rb index 0b7f06a..04a0eb3 100755 --- a/lib/tree/utils/tree_merge_handler.rb +++ b/lib/tree/utils/tree_merge_handler.rb @@ -35,6 +35,8 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # +require_relative '../../../lib/tree/utils/utils' + # Provides utility methods to merge two {Tree::TreeNode} based trees. # @since 0.9.0 module Tree::Utils::TreeMergeHandler @@ -60,8 +62,7 @@ module Tree::Utils::TreeMergeHandler # have the same root node as self. def merge(other_tree) check_merge_prerequisites(other_tree) - new_tree = merge_trees(self.root.dup, other_tree.root) - return new_tree + merge_trees(self.root.dup, other_tree.root) end # Merge in another tree (that shares the same root node) into +this+ tree. @@ -102,7 +103,7 @@ def check_merge_prerequisites(other_tree) end end - # Utility function to recursivley merge two subtrees. + # Utility function to recursively merge two subtrees. # # @author Darren Oakley (https://github.com/dazoakley) # @@ -123,7 +124,7 @@ def merge_trees(tree1, tree2) merge_trees( child, tree2[child.name] ) unless tree2[child.name].nil? end - return tree1 + tree1 end end diff --git a/lib/tree/utils/utils.rb b/lib/tree/utils/utils.rb index d59a791..71ae433 100644 --- a/lib/tree/utils/utils.rb +++ b/lib/tree/utils/utils.rb @@ -36,6 +36,9 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Provides utilities and mixin modules for RubyTree. + +require_relative '../../../lib/tree' + module Tree::Utils # Empty module. Being used as a namespace. end diff --git a/lib/tree/version.rb b/lib/tree/version.rb index ada85a5..a82bf92 100644 --- a/lib/tree/version.rb +++ b/lib/tree/version.rb @@ -4,7 +4,7 @@ # # Author:: Anupam Sengupta (anupamsg@gmail.com) # -# Copyright (c) 2012, 2013, 2014, 2015 Anupam Sengupta +# Copyright (c) 2012, 2013, 2014, 2015, 2017 Anupam Sengupta # # All rights reserved. # @@ -37,5 +37,5 @@ # module Tree # Rubytree Package Version - VERSION = '0.9.7' + VERSION = '1.0.0' end diff --git a/rubytree.gemspec b/rubytree.gemspec index d125693..56ce318 100644 --- a/rubytree.gemspec +++ b/rubytree.gemspec @@ -4,15 +4,14 @@ # # Author:: Anupam Sengupta (anupamsg@gmail.com) # -# Copyright (c) 2012, 2013, 2014, 2015 Anupam Sengupta +# Copyright (c) 2012, 2013, 2014, 2015, 2017 Anupam Sengupta # All rights reserved. -$:.unshift File.expand_path("../lib", __FILE__) -require "tree/version" +require './lib/tree/version' Gem::Specification.new do |s| s.name = 'rubytree' - s.date = '2015-12-31' + s.date = '2017-12-21' s.version = Tree::VERSION s.license = 'BSD' @@ -21,7 +20,7 @@ Gem::Specification.new do |s| s.email = 'anupamsg@gmail.com' s.homepage = 'http://rubytree.anupamsg.me' - s.required_ruby_version = '>=1.8.7' + s.required_ruby_version = '>=2.2' s.summary = %q{A generic tree data structure.} s.description = <<-EOF @@ -63,25 +62,24 @@ Gem::Specification.new do |s| s.test_files = Dir.glob('test/**/test_*.rb') - s.extra_rdoc_files = ['README.md', 'LICENSE.md', - 'API-CHANGES.rdoc', 'History.rdoc'] - s.rdoc_options = ["--title", "Rubytree Documentation", "--quiet"] + s.extra_rdoc_files = %w(README.md LICENSE.md API-CHANGES.rdoc History.rdoc) + s.rdoc_options = ['--title', 'Rubytree Documentation', '--quiet'] - s.add_runtime_dependency 'structured_warnings' , '~> 0.2' - s.add_runtime_dependency 'json' , '~> 1.8' + s.add_runtime_dependency 'structured_warnings' , '~> 0.3' + s.add_runtime_dependency 'json' , '~> 2.1' # Note: Rake is added as a development and test dependency in the Gemfile. - s.add_development_dependency 'bundler' , '~> 1.7' - s.add_development_dependency 'rdoc' , '~> 4.2' - s.add_development_dependency 'yard' , '~> 0.8' + s.add_development_dependency 'bundler' , '~> 1.16' + s.add_development_dependency 'rdoc' , '~> 6.0' + s.add_development_dependency 'yard' , '~> 0.9' s.add_development_dependency 'rtagstask' , '~> 0.0' - s.add_development_dependency 'rspec' , '~> 3.4' + s.add_development_dependency 'rspec' , '~> 3.7' s.post_install_message = <<-EOF ======================================================================== Thank you for installing RubyTree. - Note:: As of 0.9.5, the Tree::TreeNode#add method has 'move' semantics. + Note:: As of 1.0.0, RubyTree can only support MRI Ruby >= 2.2.x Details of the API changes are documented in the API-CHANGES file. ======================================================================== diff --git a/setup.rb b/setup.rb index 424a5f3..6531fd9 100644 --- a/setup.rb +++ b/setup.rb @@ -281,7 +281,6 @@ def multipackage_entries 'site-ruby-common' => 'siteruby', # For backward compatibility 'site-ruby' => 'siterubyver', # For backward compatibility 'bin-dir' => 'bindir', - 'bin-dir' => 'bindir', 'rb-dir' => 'rbdir', 'so-dir' => 'sodir', 'data-dir' => 'datadir', diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index ff1a414..e929193 100755 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -7,4 +7,4 @@ # Copyright (C) 2015 Anupam Sengupta # -require "tree" +require 'tree' diff --git a/spec/tree_spec.rb b/spec/tree_spec.rb index 742c668..ecee3d0 100755 --- a/spec/tree_spec.rb +++ b/spec/tree_spec.rb @@ -7,12 +7,12 @@ # Copyright (C) 2015 Anupam Sengupta # -require "rspec" -require "spec_helper" +require 'rspec' +require 'spec_helper' describe Tree do - shared_examples_for "any detached node" do + shared_examples_for 'any detached node' do it 'should not equal "Object.new"' do expect(@tree).not_to eq(Object.new) end @@ -22,53 +22,53 @@ it 'identifies itself as a root node' do expect(@tree.is_root?).to eq(true) end - it "does not have a parent node" do + it 'does not have a parent node' do expect(@tree.parent).to eq(nil) end end - context "#initialize", "with empty name and nil content" do + context '#initialize', 'with empty name and nil content' do before(:each) do - @tree = Tree::TreeNode.new("") + @tree = Tree::TreeNode.new('') end it 'creates the tree node with name as ""' do - expect(@tree.name).to eq("") + expect(@tree.name).to eq('') end it "has 'nil' content" do expect(@tree.content).to eq(nil) end - it_behaves_like "any detached node" + it_behaves_like 'any detached node' end - context "#initialize", "with name 'A' and nil content" do + context '#initialize', "with name 'A' and nil content" do before(:each) do - @tree = Tree::TreeNode.new("A") + @tree = Tree::TreeNode.new('A') end it 'creates the tree node with name as "A"' do - expect(@tree.name).to eq("A") + expect(@tree.name).to eq('A') end it "has 'nil' content" do expect(@tree.content).to eq(nil) end - it_behaves_like "any detached node" + it_behaves_like 'any detached node' end - context "#initialize", "with node name 'A' and some content" do + context '#initialize', "with node name 'A' and some content" do before(:each) do - @sample = "sample" - @tree = Tree::TreeNode.new("A", @sample) + @sample = 'sample' + @tree = Tree::TreeNode.new('A', @sample) end it 'creates the tree node with name as "A"' do - expect(@tree.name).to eq("A") + expect(@tree.name).to eq('A') end it "has some content #{@sample}" do expect(@tree.content).to eq(@sample) end - it_behaves_like "any detached node" + it_behaves_like 'any detached node' end end diff --git a/test/run_test.rb b/test/run_test.rb index 31d93be..16235c9 100755 --- a/test/run_test.rb +++ b/test/run_test.rb @@ -32,13 +32,13 @@ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -base_dir = File.expand_path(File.join(File.dirname(__FILE__), "..")) -lib_dir = File.join(base_dir, "lib") -test_dir = File.join(base_dir, "test") +base_dir = File.expand_path(File.join(File.dirname(__FILE__), '..')) +lib_dir = File.join(base_dir, 'lib') +test_dir = File.join(base_dir, 'test') $LOAD_PATH.unshift(lib_dir) -if ENV["COVERAGE"] +if ENV['COVERAGE'] begin require 'simplecov' require 'coveralls' @@ -51,10 +51,10 @@ add_group 'Internal Utilities', '/lib/tree/utils/.*.rb' end rescue LoadError => e - puts "Could not load simplecov; continuing without code coverage" + puts 'Could not load simplecov; continuing without code coverage' + e.cause end end require 'test/unit' -exit Test::Unit::AutoRunner.run(true, test_dir) +Test::Unit::AutoRunner.run(true, test_dir) diff --git a/test/test_binarytree.rb b/test/test_binarytree.rb index 193deed..f5fb9de 100755 --- a/test/test_binarytree.rb +++ b/test/test_binarytree.rb @@ -3,7 +3,7 @@ # test_binarytree.rb - This file is part of the RubyTree package. # # -# Copyright (c) 2006, 2007, 2008, 2009, 2010, 2012, 2013, 2015 Anupam Sengupta +# Copyright (c) 2006, 2007, 2008, 2009, 2010, 2012, 2013, 2015, 2017 Anupam Sengupta # # All rights reserved. # @@ -34,7 +34,7 @@ # require 'test/unit' -require 'tree/binarytree' +require_relative '../lib/tree/binarytree' module TestTree # Test class for the binary tree node. @@ -42,10 +42,10 @@ class TestBinaryTreeNode < Test::Unit::TestCase # Setup the test data scaffolding. def setup - @root = Tree::BinaryTreeNode.new("ROOT", "Root Node") + @root = Tree::BinaryTreeNode.new('ROOT', 'Root Node') - @left_child1 = Tree::BinaryTreeNode.new("A Child at Left", "Child Node @ left") - @right_child1 = Tree::BinaryTreeNode.new("B Child at Right", "Child Node @ right") + @left_child1 = Tree::BinaryTreeNode.new('A Child at Left', 'Child Node @ left') + @right_child1 = Tree::BinaryTreeNode.new('B Child at Right', 'Child Node @ right') end # Tear down the test data scaffolding. @@ -58,22 +58,22 @@ def teardown # Test initialization of the binary tree. def test_initialize assert_not_nil(@root, "Binary tree's Root should have been created") - assert_nil(@root.left_child, "The initial left child of root should be nil") - assert_nil(@root.right_child, "The initial right child of root should be nil") - assert_equal(@root.children.size, 0, "Initially no children should be present") + assert_nil(@root.left_child, 'The initial left child of root should be nil') + assert_nil(@root.right_child, 'The initial right child of root should be nil') + assert_equal(@root.children.size, 0, 'Initially no children should be present') end def test_from_hash # Can't make a root node without a name assert_raise (ArgumentError) { Tree::BinaryTreeNode.from_hash({})} # Can't have multiple roots - assert_raise (ArgumentError) { Tree::BinaryTreeNode.from_hash({:A => {}, :B => {}}) } + assert_raise (ArgumentError) { Tree::BinaryTreeNode.from_hash({A: {}, B: {}}) } # Can't have more than 2 children - too_many_kids = {:A => {:B => {}, :C => {}, :D => {} } } + too_many_kids = {A: {B: {}, C: {}, D: {}}} assert_raise(ArgumentError) { Tree::BinaryTreeNode.from_hash(too_many_kids) } - valid_hash = {:A => {:B => {}, :C => { :D => {} } } } + valid_hash = {A: {B: {}, C: {D: {}}}} tree = Tree::BinaryTreeNode.from_hash(valid_hash) # A # / \ @@ -88,19 +88,19 @@ def test_from_hash assert_equal(2, tree.children.count) # B, C, D assert_equal(4, tree.size) - valid_hash_with_content = {[:A, "Content!"] => {:B => {}, :C => { [:D, "More content"] => {} } } } + valid_hash_with_content = {[:A, 'Content!'] => {B: {}, C: {[:D, 'More content'] => {}}} } tree2 = Tree::BinaryTreeNode.from_hash(valid_hash_with_content) assert_equal(Tree::BinaryTreeNode, tree2.class) - assert_equal("Content!" , tree2.content) - assert_equal("More content", tree2[:C][:D].content) + assert_equal('Content!', tree2.content) + assert_equal('More content', tree2[:C][:D].content) end def test_add_from_hash - root = Tree::BinaryTreeNode.new("Root") + root = Tree::BinaryTreeNode.new('Root') # Can't have too many children - too_many_kids = {:child1 => {}, :child2 => {}, :child3 => {}} + too_many_kids = {child1: {}, child2: {}, child3: {}} assert_raise(ArgumentError) { root.add_from_hash(too_many_kids) } assert_equal(0, root.children.count) # Nothing added @@ -108,7 +108,7 @@ def test_add_from_hash assert_equal([], root.add_from_hash({})) assert_equal(1, root.size) - valid_hash = {:A => {}, :B => { :C => {}, [:D, "leaf"] => {} } } + valid_hash = {A: {}, B: {C: {}, [:D, 'leaf'] => {}}} added = root.add_from_hash(valid_hash) # root # / \ @@ -120,48 +120,48 @@ def test_add_from_hash assert_equal(2, added.count) assert_equal(5, root.size) assert_equal(root.children.count, 2) - assert_equal("leaf", root[:B][:D].content) + assert_equal('leaf', root[:B][:D].content) # Can't add more than two children - assert_raise(ArgumentError) { root.add_from_hash({:X => {}}) } - node = Tree::BinaryTreeNode.new("Root 2") - assert_raise(ArgumentError) { node.add_from_hash({:A => {}, :B => {}, :C => {}}) } + assert_raise(ArgumentError) { root.add_from_hash({X: {}}) } + node = Tree::BinaryTreeNode.new('Root 2') + assert_raise(ArgumentError) { node.add_from_hash({A: {}, B: {}, C: {}}) } end # Test the add method. def test_add @root.add @left_child1 - assert(!@left_child1.is_root?, "Left child1 cannot be a root after addition to the ROOT node") + assert(!@left_child1.is_root?, 'Left child1 cannot be a root after addition to the ROOT node') - assert_same(@left_child1, @root.left_child, "The left node should be left_child1") - assert_same(@left_child1, @root.first_child, "The first node should be left_child1") + assert_same(@left_child1, @root.left_child, 'The left node should be left_child1') + assert_same(@left_child1, @root.first_child, 'The first node should be left_child1') @root.add @right_child1 - assert(!@right_child1.is_root?, "Right child1 cannot be a root after addition to the ROOT node") + assert(!@right_child1.is_root?, 'Right child1 cannot be a root after addition to the ROOT node') - assert_same(@right_child1, @root.right_child, "The right node should be right_child1") - assert_same(@right_child1, @root.last_child, "The first node should be right_child1") + assert_same(@right_child1, @root.right_child, 'The right node should be right_child1') + assert_same(@right_child1, @root.last_child, 'The first node should be right_child1') assert_raise ArgumentError do - @root.add Tree::BinaryTreeNode.new("The third child!") + @root.add Tree::BinaryTreeNode.new('The third child!') end assert_raise ArgumentError do - @root << Tree::BinaryTreeNode.new("The third child!") + @root << Tree::BinaryTreeNode.new('The third child!') end end # Test the inordered_each method. def test_inordered_each - a = Tree::BinaryTreeNode.new("a") - b = Tree::BinaryTreeNode.new("b") - c = Tree::BinaryTreeNode.new("c") - d = Tree::BinaryTreeNode.new("d") - e = Tree::BinaryTreeNode.new("e") - f = Tree::BinaryTreeNode.new("f") - g = Tree::BinaryTreeNode.new("g") - h = Tree::BinaryTreeNode.new("h") - i = Tree::BinaryTreeNode.new("i") + a = Tree::BinaryTreeNode.new('a') + b = Tree::BinaryTreeNode.new('b') + c = Tree::BinaryTreeNode.new('c') + d = Tree::BinaryTreeNode.new('d') + e = Tree::BinaryTreeNode.new('e') + f = Tree::BinaryTreeNode.new('f') + g = Tree::BinaryTreeNode.new('g') + h = Tree::BinaryTreeNode.new('h') + i = Tree::BinaryTreeNode.new('i') # Create the following Tree # f <-- level 0 (Root) @@ -186,9 +186,9 @@ def test_inordered_each assert_equal(f, result) # each should return the original object - expected_array.each_index do |i| + expected_array.each_index do |idx| # Match only the names. - assert_equal(expected_array[i].name, result_array[i].name) + assert_equal(expected_array[idx].name, result_array[idx].name) end assert_equal(Enumerator, f.inordered_each.class) if defined?(Enumerator.class )# Without a block @@ -200,7 +200,7 @@ def test_left_child @root << @left_child1 @root << @right_child1 assert_same(@left_child1, @root.left_child, "The left child should be 'left_child1") - assert_not_same(@right_child1, @root.left_child, "The right_child1 is not the left child") + assert_not_same(@right_child1, @root.left_child, 'The right_child1 is not the left child') end # Test the right_child method. @@ -208,7 +208,7 @@ def test_right_child @root << @left_child1 @root << @right_child1 assert_same(@right_child1, @root.right_child, "The right child should be 'right_child1") - assert_not_same(@left_child1, @root.right_child, "The left_child1 is not the left child") + assert_not_same(@left_child1, @root.right_child, 'The left_child1 is not the left child') end # Test left_child= method. @@ -216,18 +216,18 @@ def test_left_child_equals @root << @left_child1 @root << @right_child1 assert_same(@left_child1, @root.left_child, "The left child should be 'left_child1") - assert(!@left_child1.is_root?, "The left child now cannot be a root.") + assert(!@left_child1.is_root?, 'The left child now cannot be a root.') - @root.left_child = Tree::BinaryTreeNode.new("New Left Child") - assert(!@root.left_child.is_root?, "The left child now cannot be a root.") - assert_equal("New Left Child", @root.left_child.name, "The left child should now be the new child") - assert_equal("B Child at Right", @root.last_child.name, "The last child should now be the right child") + @root.left_child = Tree::BinaryTreeNode.new('New Left Child') + assert(!@root.left_child.is_root?, 'The left child now cannot be a root.') + assert_equal('New Left Child', @root.left_child.name, 'The left child should now be the new child') + assert_equal('B Child at Right', @root.last_child.name, 'The last child should now be the right child') # Now set the left child as nil, and retest @root.left_child = nil - assert_nil(@root.left_child, "The left child should now be nil") - assert_nil(@root.first_child, "The first child is now nil") - assert_equal("B Child at Right", @root.last_child.name, "The last child should now be the right child") + assert_nil(@root.left_child, 'The left child should now be nil') + assert_nil(@root.first_child, 'The first child is now nil') + assert_equal('B Child at Right', @root.last_child.name, 'The last child should now be the right child') end # Test right_child= method. @@ -235,19 +235,19 @@ def test_right_child_equals @root << @left_child1 @root << @right_child1 assert_same(@right_child1, @root.right_child, "The right child should be 'right_child1") - assert(!@right_child1.is_root?, "The right child now cannot be a root.") + assert(!@right_child1.is_root?, 'The right child now cannot be a root.') - @root.right_child = Tree::BinaryTreeNode.new("New Right Child") - assert(!@root.right_child.is_root?, "The right child now cannot be a root.") - assert_equal("New Right Child", @root.right_child.name, "The right child should now be the new child") - assert_equal("A Child at Left", @root.first_child.name, "The first child should now be the left child") - assert_equal("New Right Child", @root.last_child.name, "The last child should now be the right child") + @root.right_child = Tree::BinaryTreeNode.new('New Right Child') + assert(!@root.right_child.is_root?, 'The right child now cannot be a root.') + assert_equal('New Right Child', @root.right_child.name, 'The right child should now be the new child') + assert_equal('A Child at Left', @root.first_child.name, 'The first child should now be the left child') + assert_equal('New Right Child', @root.last_child.name, 'The last child should now be the right child') # Now set the right child as nil, and retest @root.right_child = nil - assert_nil(@root.right_child, "The right child should now be nil") - assert_equal("A Child at Left", @root.first_child.name, "The first child should now be the left child") - assert_nil(@root.last_child, "The first child is now nil") + assert_nil(@root.right_child, 'The right child should now be nil') + assert_equal('A Child at Left', @root.first_child.name, 'The first child should now be the left child') + assert_nil(@root.last_child, 'The first child is now nil') end # Test isLeft_child? method. @@ -255,14 +255,14 @@ def test_is_left_child_eh @root << @left_child1 @root << @right_child1 - assert(@left_child1.is_left_child?, "left_child1 should be the left child") - assert(!@right_child1.is_left_child?, "left_child1 should be the left child") + assert(@left_child1.is_left_child?, 'left_child1 should be the left child') + assert(!@right_child1.is_left_child?, 'left_child1 should be the left child') # Now set the right child as nil, and retest @root.right_child = nil - assert(@left_child1.is_left_child?, "left_child1 should be the left child") + assert(@left_child1.is_left_child?, 'left_child1 should be the left child') - assert(!@root.is_left_child?, "Root is neither left child nor right") + assert(!@root.is_left_child?, 'Root is neither left child nor right') end # Test is_right_child? method. @@ -270,13 +270,13 @@ def test_is_right_child_eh @root << @left_child1 @root << @right_child1 - assert(@right_child1.is_right_child?, "right_child1 should be the right child") - assert(!@left_child1.is_right_child?, "right_child1 should be the right child") + assert(@right_child1.is_right_child?, 'right_child1 should be the right child') + assert(!@left_child1.is_right_child?, 'right_child1 should be the right child') # Now set the left child as nil, and retest @root.left_child = nil - assert(@right_child1.is_right_child?, "right_child1 should be the right child") - assert(!@root.is_right_child?, "Root is neither left child nor right") + assert(@right_child1.is_right_child?, 'right_child1 should be the right child') + assert(!@root.is_right_child?, 'Root is neither left child nor right') end # Test swap_children method. @@ -284,35 +284,37 @@ def test_swap_children @root << @left_child1 @root << @right_child1 - assert(@right_child1.is_right_child?, "right_child1 should be the right child") - assert(!@left_child1.is_right_child?, "right_child1 should be the right child") + assert(@right_child1.is_right_child?, 'right_child1 should be the right child') + assert(!@left_child1.is_right_child?, 'right_child1 should be the right child') @root.swap_children - assert(@right_child1.is_left_child?, "right_child1 should now be the left child") - assert(@left_child1.is_right_child?, "left_child1 should now be the right child") - assert_equal(@right_child1, @root.first_child, "right_child1 should now be the first child") - assert_equal(@left_child1, @root.last_child, "left_child1 should now be the last child") - assert_equal(@right_child1, @root[0], "right_child1 should now be the first child") - assert_equal(@left_child1, @root[1], "left_child1 should now be the last child") + assert(@right_child1.is_left_child?, 'right_child1 should now be the left child') + assert(@left_child1.is_right_child?, 'left_child1 should now be the right child') + assert_equal(@right_child1, @root.first_child, 'right_child1 should now be the first child') + assert_equal(@left_child1, @root.last_child, 'left_child1 should now be the last child') + assert_equal(@right_child1, @root[0], 'right_child1 should now be the first child') + assert_equal(@left_child1, @root[1], 'left_child1 should now be the last child') end # Test the old CamelCase method names - def test_old_camelCase_method_names - @left_child2 = Tree::BinaryTreeNode.new("A Child at Left", "Child Node @ left") - @right_child2 = Tree::BinaryTreeNode.new("B Child at Right", "Child Node @ right") + def test_old_camel_case_names + @left_child2 = Tree::BinaryTreeNode.new('A Child at Left', 'Child Node @ left') + @right_child2 = Tree::BinaryTreeNode.new('B Child at Right', 'Child Node @ right') require 'structured_warnings' meth_names_for_test = %w{leftChild isLeftChild? rightChild isRightChild?} meth_names_for_test.each do |meth_name| - assert_warn(DeprecatedMethodWarning) {@root.send(meth_name)} + assert_warn(StructuredWarnings::DeprecatedMethodWarning) {@root.send(meth_name)} end - assert_warn(DeprecatedMethodWarning) {@root.leftChild = @left_child2} - assert_warn(DeprecatedMethodWarning) {@root.rightChild = @right_child2} - assert_raise(NoMethodError) {@root.to_snake_case("ABCD")} # Make sure the right method is visible + # noinspection RubyResolve + assert_warn(StructuredWarnings::DeprecatedMethodWarning) {@root.leftChild = @left_child2} + # noinspection RubyResolve + assert_warn(StructuredWarnings::DeprecatedMethodWarning) {@root.rightChild = @right_child2} + assert_raise(NoMethodError) {@root.DummyMethodDoesNotExist} # Make sure the right method is visible end diff --git a/test/test_rubytree_require.rb b/test/test_rubytree_require.rb index cf450a5..45479cc 100755 --- a/test/test_rubytree_require.rb +++ b/test/test_rubytree_require.rb @@ -33,7 +33,7 @@ # require 'test/unit' -require 'rubytree' +require_relative '../lib/rubytree' module TestTree @@ -42,7 +42,7 @@ class TestRequireRubytree < Test::Unit::TestCase # A simple test. We are just checking whether the require worked. def test_create_a_simple_node - assert_not_nil(Tree::TreeNode.new("Root", "A Root node")) + assert_not_nil(Tree::TreeNode.new('Root', 'A Root node')) end end end diff --git a/test/test_subclassed_node.rb b/test/test_subclassed_node.rb index 137d15b..3245d43 100755 --- a/test/test_subclassed_node.rb +++ b/test/test_subclassed_node.rb @@ -2,7 +2,7 @@ # test_subclassed_node.rb - This file is part of the RubyTree package. # -# Copyright (c) 2012 Anupam Sengupta +# Copyright (c) 2012, 2017 Anupam Sengupta # # All rights reserved. # @@ -34,7 +34,7 @@ require 'test/unit' require 'json' -require 'tree' +require_relative '../lib/tree' module TestTree @@ -45,27 +45,28 @@ class TestSubclassedTreeNode < Test::Unit::TestCase class MyNode < Tree::TreeNode # A dummy method to test the camelCasedMethod resolution def my_dummy_method - "Hello" + 'Hello' end end - def test_subclassed_camelcase_methods - root = MyNode.new("Root") + def test_camelcase_methods + root = MyNode.new('Root') - assert_equal("Hello", root.my_dummy_method) + assert_equal('Hello', root.my_dummy_method) # We should get a warning as we are invoking the camelCase version of the dummy method. - assert_warn(DeprecatedMethodWarning) { root.send('MyDummyMethod') } + assert_warn(StructuredWarnings::DeprecatedMethodWarning) { root.send('MyDummyMethod') } - # Test if the structured_warnings can be disabled to call the CamelCa - DeprecatedMethodWarning.disable do - assert_equal("Hello", root.myDummyMethod) + # Test if the structured_warnings can be disabled to call the CamelCase methods. + StructuredWarnings::DeprecatedMethodWarning.disable do + # noinspection RubyResolve + assert_equal('Hello', root.myDummyMethod) end end - def test_subclassed_detached_copy_is_same_class - root = MyNode.new("Root") + def test_detached_copy_same_clz + root = MyNode.new('Root') assert_equal(MyNode, root.detached_copy.class) end diff --git a/test/test_thread_and_fiber.rb b/test/test_thread_and_fiber.rb index 534f034..8864e8d 100755 --- a/test/test_thread_and_fiber.rb +++ b/test/test_thread_and_fiber.rb @@ -34,7 +34,7 @@ require 'test/unit' require 'json' -require 'tree' +require_relative '../lib/tree' module TestTree # Test class for the Tree node. @@ -42,7 +42,7 @@ class TestFiberAndThreadOnNode < Test::Unit::TestCase # Test long and unbalanced trees def create_long_depth_trees(depth=100) - tree = Tree::TreeNode.new("/") + tree = Tree::TreeNode.new('/') current = tree depth.times do |i| new_node = Tree::TreeNode.new("#{i}") @@ -50,7 +50,7 @@ def create_long_depth_trees(depth=100) current = new_node end - tree.each { |n| nil } + tree.each { |_| nil } tree end diff --git a/test/test_tree.rb b/test/test_tree.rb index dd4f62e..01b535b 100755 --- a/test/test_tree.rb +++ b/test/test_tree.rb @@ -2,7 +2,7 @@ # test_tree.rb - This file is part of the RubyTree package. # -# Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Anupam Sengupta +# Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Anupam Sengupta # # All rights reserved. # @@ -33,11 +33,13 @@ # require 'test/unit' +require 'structured_warnings' require 'json' -require 'tree' +require_relative '../lib/tree/tree_deps' module TestTree # Test class for the Tree node. + # noinspection RubyTooManyInstanceVariablesInspection class TestTreeNode < Test::Unit::TestCase Person = Struct::new(:First, :last) # A simple structure to use as the content for the nodes. @@ -63,13 +65,13 @@ class TestTreeNode < Test::Unit::TestCase # # Some basic setup to create the nodes for the test tree. def setup - @root = Tree::TreeNode.new("ROOT", "Root Node") + @root = Tree::TreeNode.new('ROOT', 'Root Node') - @child1 = Tree::TreeNode.new("Child1", "Child Node 1") - @child2 = Tree::TreeNode.new("Child2", "Child Node 2") - @child3 = Tree::TreeNode.new("Child3", "Child Node 3") - @child4 = Tree::TreeNode.new("Child4", "Grand Child 1") - @child5 = Tree::TreeNode.new("Child5", "Child Node 4") + @child1 = Tree::TreeNode.new('Child1', 'Child Node 1') + @child2 = Tree::TreeNode.new('Child2', 'Child Node 2') + @child3 = Tree::TreeNode.new('Child3', 'Child Node 3') + @child4 = Tree::TreeNode.new('Child4', 'Grand Child 1') + @child5 = Tree::TreeNode.new('Child5', 'Child Node 4') end @@ -92,17 +94,17 @@ def test_has_version_number # This test is for the root alone - without any children being linked def test_root_setup - assert_not_nil(@root , "Root cannot be nil") - assert_nil(@root.parent , "Parent of root node should be nil") - assert_not_nil(@root.name , "Name should not be nil") - assert_equal("ROOT" , @root.name, "Name should be 'ROOT'") - assert_equal("Root Node" , @root.content, "Content should be 'Root Node'") - assert(@root.is_root? , "Should identify as root") - assert(!@root.has_children? , "Cannot have any children") - assert(@root.has_content? , "This root should have content") - assert_equal(1 , @root.size, "Number of nodes should be one") - assert_equal(0, @root.siblings.length, "This root does not have any children") - assert_equal(0, @root.in_degree, "Root should have an in-degree of 0") + assert_not_nil(@root , 'Root cannot be nil') + assert_nil(@root.parent , 'Parent of root node should be nil') + assert_not_nil(@root.name , 'Name should not be nil') + assert_equal('ROOT', @root.name, "Name should be 'ROOT'") + assert_equal('Root Node', @root.content, "Content should be 'Root Node'") + assert(@root.is_root? , 'Should identify as root') + assert(!@root.has_children? , 'Cannot have any children') + assert(@root.has_content? , 'This root should have content') + assert_equal(1 , @root.size, 'Number of nodes should be one') + assert_equal(0, @root.siblings.length, 'This root does not have any children') + assert_equal(0, @root.in_degree, 'Root should have an in-degree of 0') assert_equal(0, @root.node_height, "Root's height before adding any children is 0") assert_raise(ArgumentError) { Tree::TreeNode.new(nil) } end @@ -115,8 +117,8 @@ def test_root # return nil so that the possibility of a recursive error does not exist # at all. assert_same(@root , @root.root, "Root's root is self") - assert_same(@root , @child1.root, "Root should be ROOT") - assert_same(@root , @child4.root, "Root should be ROOT") + assert_same(@root , @child1.root, 'Root should be ROOT') + assert_same(@root , @child4.root, 'Root should be ROOT') assert_equal(2 , @root.node_height, "Root's height after adding the children should be 2") end @@ -129,18 +131,18 @@ def test_from_hash # / \ # H I - hash = {[:A, "Root content"] => { - :B => { - :E => {}, - :F => { - :H => {}, - [:I, "Leaf content"] => {} - } - }, - :C => {}, - :D => { - :G => {} - } + hash = {[:A, 'Root content'] => { + B: { + E: {}, + F: { + H: {}, + [:I, 'Leaf content'] => {} + } + }, + C: {}, + D: { + G: {} + } } } @@ -151,11 +153,11 @@ def test_from_hash assert_equal(true, tree.is_root?) assert_equal(false, tree.is_leaf?) assert_equal(9, tree.size) - assert_equal("Root content", tree.content) + assert_equal('Root content', tree.content) assert_equal(3, tree.children.count) # B, C, D leaf_with_content = tree[:B][:F][:I] - assert_equal("Leaf content", leaf_with_content.content) + assert_equal('Leaf content', leaf_with_content.content) assert_equal(true, leaf_with_content.is_leaf?) leaf_without_content = tree[:C] @@ -168,7 +170,7 @@ def test_from_hash # Can't make a node without a name assert_raise (ArgumentError) { Tree::TreeNode.from_hash({}) } # Can't have multiple roots - assert_raise (ArgumentError) { Tree::TreeNode.from_hash({:A => {}, :B => {}}) } + assert_raise (ArgumentError) { Tree::TreeNode.from_hash({A: {}, B: {}}) } end @@ -181,18 +183,18 @@ def test_from_hash_with_nils # / \ # H I - hash = {[:A, "Root content"] => { - :B => { - :E => nil, - :F => { - :H => nil, - [:I, "Leaf content"] => nil - } - }, - :C => nil, - :D => { - :G => nil - } + hash = {[:A, 'Root content'] => { + B: { + E: nil, + F: { + H: nil, + [:I, 'Leaf content'] => nil + } + }, + C: nil, + D: { + G: nil + } } } @@ -203,11 +205,11 @@ def test_from_hash_with_nils assert_equal(true, tree.is_root?) assert_equal(false, tree.is_leaf?) assert_equal(9, tree.size) - assert_equal("Root content", tree.content) + assert_equal('Root content', tree.content) assert_equal(3, tree.children.count) # B, C, D leaf_with_content = tree[:B][:F][:I] - assert_equal("Leaf content", leaf_with_content.content) + assert_equal('Leaf content', leaf_with_content.content) assert_equal(true, leaf_with_content.is_leaf?) leaf_without_content = tree[:C] @@ -226,7 +228,7 @@ def test_add_from_hash assert_equal([], tree.add_from_hash(hash)) # Okay, now try a real hash - hash = {:B => {:C => {:D => nil}, :E => {}, :F => {}}, [:G, "G content"] => {}} + hash = {B: {C: {D: nil}, E: {}, F: {}}, [:G, 'G content'] => {}} # A # / \ # B G @@ -239,14 +241,14 @@ def test_add_from_hash assert_equal(Array, added_children.class) assert_equal(2, added_children.count) assert_equal(7, tree.size) - assert_equal("G content", tree[:G].content) + assert_equal('G content', tree[:G].content) assert_equal(true, tree[:G].is_leaf?) assert_equal(5, tree[:B].size) assert_equal(3, tree[:B].children.count) assert_raise (ArgumentError) { tree.add_from_hash([]) } - assert_raise (ArgumentError) { tree.add_from_hash("not a hash") } - assert_raise (ArgumentError) { tree.add_from_hash({:X => "Not a hash or nil"}) } + assert_raise (ArgumentError) { tree.add_from_hash('not a hash') } + assert_raise (ArgumentError) { tree.add_from_hash({X: 'Not a hash or nil'}) } end # Test exporting to ruby Hash @@ -254,7 +256,7 @@ def test_to_h a = Tree::TreeNode.new(:A) b = Tree::TreeNode.new(:B) c = Tree::TreeNode.new(:C) - d = Tree::TreeNode.new(:D) + # d = Tree::TreeNode.new(:D) e = Tree::TreeNode.new(:E) f = Tree::TreeNode.new(:F) g = Tree::TreeNode.new(:G) @@ -271,7 +273,7 @@ def test_to_h b << e exported = a.to_h - expected = {:A => {:B => {:E => {}}, :C => {:F => {}, :G => {}}}} + expected = {A: {B: {E: {}}, C: {F: {}, G: {}}}} assert_equal(expected, exported) end @@ -285,7 +287,7 @@ def test_to_h_from_hash_symmetry # |\ | # I J K - input = {:A => {:B => {:E => {:I => {}, :J =>{}}, :F => {}, :G => {}}, :C =>{:H => {:K => {}}}}} + input = {A: {B: {E: {I: {}, J: {}}, F: {}, G: {}}, C: {H: {K: {}}}}} node = Tree::TreeNode.from_hash(input) assert_equal(input, node.to_h) @@ -293,25 +295,25 @@ def test_to_h_from_hash_symmetry # Test the presence of content in the nodes. def test_has_content_eh - a_node = Tree::TreeNode.new("A Node") - assert_nil(a_node.content , "The node should not have content") - assert(!a_node.has_content? , "The node should not have content") + a_node = Tree::TreeNode.new('A Node') + assert_nil(a_node.content , 'The node should not have content') + assert(!a_node.has_content? , 'The node should not have content') - a_node.content = "Something" - assert_not_nil(a_node.content, "The node should now have content") - assert(a_node.has_content?, "The node should now have content") + a_node.content = 'Something' + assert_not_nil(a_node.content, 'The node should now have content') + assert(a_node.has_content?, 'The node should now have content') end # Test the equivalence of size and length methods. def test_length_is_size setup_test_tree - assert_equal(@root.size, @root.length, "Length and size methods should return the same result") + assert_equal(@root.size, @root.length, 'Length and size methods should return the same result') end # Test the <=> operator. def test_spaceship require 'structured_warnings' - StandardWarning.disable # Disable the warnings for using integers as node names + StructuredWarnings::StandardWarning.disable # Disable the warnings for using integers as node names first_node = Tree::TreeNode.new(1) second_node = Tree::TreeNode.new(2) @@ -322,66 +324,66 @@ def test_spaceship second_node = Tree::TreeNode.new(1) assert_equal(0, first_node <=> second_node) - first_node = Tree::TreeNode.new("ABC") - second_node = Tree::TreeNode.new("XYZ") + first_node = Tree::TreeNode.new('ABC') + second_node = Tree::TreeNode.new('XYZ') assert_nil(first_node <=> nil) assert_equal(-1, first_node <=> second_node) - second_node = Tree::TreeNode.new("ABC") + second_node = Tree::TreeNode.new('ABC') assert_equal(0, first_node <=> second_node) - StandardWarning.enable + StructuredWarnings::StandardWarning.enable end # Test the inclusion of Comparable def test_is_comparable - nodeA = Tree::TreeNode.new("NodeA", "Some Content") - nodeB = Tree::TreeNode.new("NodeB", "Some Content") - nodeC = Tree::TreeNode.new("NodeC", "Some Content") + node_a = Tree::TreeNode.new('NodeA', 'Some Content') + node_b = Tree::TreeNode.new('NodeB', 'Some Content') + node_c = Tree::TreeNode.new('NodeC', 'Some Content') # Check if the nodes compare correctly - assert(nodeA < nodeB, "Node A is lexically 'less than' node B") - assert(nodeA <= nodeB, "Node A is lexically 'less than' node B") - assert(nodeB > nodeA, "Node B is lexically 'greater than' node A") - assert(nodeB >= nodeA, "Node B is lexically 'greater than' node A") + assert(node_a < node_b, "Node A is lexically 'less than' node B") + assert(node_a <= node_b, "Node A is lexically 'less than' node B") + assert(node_b > node_a, "Node B is lexically 'greater than' node A") + assert(node_b >= node_a, "Node B is lexically 'greater than' node A") - assert(!(nodeA == nodeB), "Node A and Node B are not equal") - assert(nodeB.between?(nodeA, nodeC), "Node B is lexically between node A and node C") + assert(!(node_a == node_b), 'Node A and Node B are not equal') + assert(node_b.between?(node_a, node_c), 'Node B is lexically between node A and node C') end # Test the to_s method. This is probably a little fragile right now. def test_to_s - a_node = Tree::TreeNode.new("A Node", "Some Content") + a_node = Tree::TreeNode.new('A Node', 'Some Content') - expected_string = "Node Name: A Node Content: Some Content Parent: Children: 0 Total Nodes: 1" + expected_string = 'Node Name: A Node Content: Some Content Parent: Children: 0 Total Nodes: 1' - assert_equal(expected_string, a_node.to_s, "The string representation should be same") + assert_equal(expected_string, a_node.to_s, 'The string representation should be same') # Now test with a symbol as a key. - a_node = Tree::TreeNode.new(:Node_Name, "Some Content") - expected_string = "Node Name: Node_Name Content: Some Content Parent: Children: 0 Total Nodes: 1" - assert_equal(expected_string, a_node.to_s, "The string representation should be same") + a_node = Tree::TreeNode.new(:Node_Name, 'Some Content') + expected_string = 'Node Name: Node_Name Content: Some Content Parent: Children: 0 Total Nodes: 1' + assert_equal(expected_string, a_node.to_s, 'The string representation should be same') # Now test with a symbol as a key and another symbol as the content. a_node = Tree::TreeNode.new(:Node_Name, :Content) - expected_string = "Node Name: Node_Name Content: Content Parent: Children: 0 Total Nodes: 1" - assert_equal(expected_string, a_node.to_s, "The string representation should be same") + expected_string = 'Node Name: Node_Name Content: Content Parent: Children: 0 Total Nodes: 1' + assert_equal(expected_string, a_node.to_s, 'The string representation should be same') # Now test with a symbol as a key, and a hash as the content. - a_hash = {:a_key => "Some Value"} + a_hash = {a_key: 'Some Value'} a_node = Tree::TreeNode.new(:Node_Name, a_hash) expected_string = "Node Name: Node_Name Content: #{a_hash} Parent: Children: 0 Total Nodes: 1" - assert_equal(expected_string, a_node.to_s, "The string representation should be same") + assert_equal(expected_string, a_node.to_s, 'The string representation should be same') # Lets now add a child to the previous node, and test the to_s for the child - child_node = Tree::TreeNode.new(:Child_node, "Child Node") + child_node = Tree::TreeNode.new(:Child_node, 'Child Node') a_node << child_node - expected_string = "Node Name: Child_node Content: Child Node Parent: Node_Name Children: 0 Total Nodes: 1" - assert_equal(expected_string, child_node.to_s, "The string representation should be same") + expected_string = 'Node Name: Child_node Content: Child Node Parent: Node_Name Children: 0 Total Nodes: 1' + assert_equal(expected_string, child_node.to_s, 'The string representation should be same') end @@ -404,8 +406,8 @@ def test_is_first_sibling_eh assert(@root.is_first_sibling?, "Root's first sibling is itself") assert( @child1.is_first_sibling?, "Child1's first sibling is itself") - assert(!@child2.is_first_sibling?, "Child2 is not the first sibling") - assert(!@child3.is_first_sibling?, "Child3 is not the first sibling") + assert(!@child2.is_first_sibling?, 'Child2 is not the first sibling') + assert(!@child3.is_first_sibling?, 'Child3 is not the first sibling') assert( @child4.is_first_sibling?, "Child4's first sibling is itself") end @@ -414,8 +416,8 @@ def test_is_last_sibling_eh setup_test_tree assert(@root.is_last_sibling?, "Root's last sibling is itself") - assert(!@child1.is_last_sibling?, "Child1 is not the last sibling") - assert(!@child2.is_last_sibling?, "Child2 is not the last sibling") + assert(!@child1.is_last_sibling?, 'Child1 is not the last sibling') + assert(!@child2.is_last_sibling?, 'Child2 is not the last sibling') assert( @child3.is_last_sibling?, "Child3's last sibling is itself") assert( @child4.is_last_sibling?, "Child4's last sibling is itself") end @@ -441,22 +443,22 @@ def test_siblings result = @child1.siblings { |sibling| siblings << sibling} assert_equal(@child1, result) - assert_equal(2, siblings.length, "Should have two siblings") - assert(siblings.include?(@child2), "Should have 2nd child as sibling") - assert(siblings.include?(@child3), "Should have 3rd child as sibling") + assert_equal(2, siblings.length, 'Should have two siblings') + assert(siblings.include?(@child2), 'Should have 2nd child as sibling') + assert(siblings.include?(@child3), 'Should have 3rd child as sibling') siblings.clear siblings = @child1.siblings assert_equal(Array, siblings.class) - assert_equal(2, siblings.length, "Should have two siblings") + assert_equal(2, siblings.length, 'Should have two siblings') siblings.clear @child4.siblings {|sibling| siblings << sibling} - assert(siblings.empty?, "Should not have any siblings") + assert(siblings.empty?, 'Should not have any siblings') siblings.clear siblings = @root.siblings - assert_equal(0, siblings.length, "Root should not have any siblings") + assert_equal(0, siblings.length, 'Root should not have any siblings') end @@ -464,51 +466,51 @@ def test_siblings def test_is_only_child_eh setup_test_tree - assert( @root.is_only_child? , "Root is an only child") - assert(!@child1.is_only_child?, "Child1 is not the only child") - assert(!@child2.is_only_child?, "Child2 is not the only child") - assert(!@child3.is_only_child?, "Child3 is not the only child") - assert( @child4.is_only_child?, "Child4 is an only child") + assert(@root.is_only_child? , 'Root is an only child') + assert(!@child1.is_only_child?, 'Child1 is not the only child') + assert(!@child2.is_only_child?, 'Child2 is not the only child') + assert(!@child3.is_only_child?, 'Child3 is not the only child') + assert(@child4.is_only_child?, 'Child4 is an only child') end # Test the next_sibling method. def test_next_sibling setup_test_tree - assert_nil(@root.next_sibling, "Root does not have any next sibling") + assert_nil(@root.next_sibling, 'Root does not have any next sibling') assert_equal(@child2, @child1.next_sibling, "Child1's next sibling is Child2") assert_equal(@child3, @child2.next_sibling, "Child2's next sibling is Child3") - assert_nil(@child3.next_sibling, "Child3 does not have a next sibling") - assert_nil(@child4.next_sibling, "Child4 does not have a next sibling") + assert_nil(@child3.next_sibling, 'Child3 does not have a next sibling') + assert_nil(@child4.next_sibling, 'Child4 does not have a next sibling') end # Test the previous_sibling method. def test_previous_sibling setup_test_tree - assert_nil(@root.previous_sibling, "Root does not have any previous sibling") - assert_nil(@child1.previous_sibling, "Child1 does not have previous sibling") + assert_nil(@root.previous_sibling, 'Root does not have any previous sibling') + assert_nil(@child1.previous_sibling, 'Child1 does not have previous sibling') assert_equal(@child1, @child2.previous_sibling, "Child2's previous sibling is Child1") assert_equal(@child2, @child3.previous_sibling, "Child3's previous sibling is Child2") - assert_nil(@child4.previous_sibling, "Child4 does not have a previous sibling") + assert_nil(@child4.previous_sibling, 'Child4 does not have a previous sibling') end # Test the add method. def test_add - assert(!@root.has_children?, "Should not have any children") + assert(!@root.has_children?, 'Should not have any children') - assert_equal(1, @root.size, "Should have 1 node (the root)") + assert_equal(1, @root.size, 'Should have 1 node (the root)') @root.add(@child1) @root << @child2 - assert(@root.has_children?, "Should have children") - assert_equal(3, @root.size, "Should have three nodes") + assert(@root.has_children?, 'Should have children') + assert_equal(3, @root.size, 'Should have three nodes') @root << @child3 << @child4 - assert_equal(5, @root.size, "Should have five nodes") - assert_equal(2, @child3.size, "Should have two nodes") + assert_equal(5, @root.size, 'Should have five nodes') + assert_equal(2, @child3.size, 'Should have two nodes') # Test the addition of a nil node. assert_raise(ArgumentError) { @root.add(nil) } @@ -528,11 +530,11 @@ def test_add_duplicate # # In this case, the two 'deep' nodes should not be considered duplicates - root = Tree::TreeNode.new("root") - one = Tree::TreeNode.new("one") - two = Tree::TreeNode.new("two") - three= Tree::TreeNode.new("three") - deep = Tree::TreeNode.new("deep") + root = Tree::TreeNode.new('root') + one = Tree::TreeNode.new('one') + two = Tree::TreeNode.new('two') + three= Tree::TreeNode.new('three') + deep = Tree::TreeNode.new('deep') root << one << deep # The same child cannot be added under any circumstance @@ -542,25 +544,25 @@ def test_add_duplicate begin root << two << deep rescue RuntimeError => e - fail("Error! The RuntimeError should not have been thrown. The same node can be added to different branches.") + fail("Error! The RuntimeError #{e} should not have been thrown. The same node can be added to different branches.") end assert_raise(ArgumentError) {root << three << three } - root.remove_all! # Because the first child 'three' whould have been added. + root.remove_all! # Because the first child 'three' would have been added. begin - three_dup = Tree::TreeNode.new("three") + three_dup = Tree::TreeNode.new('three') root << three << three_dup rescue RuntimeError => e - fail("Error! The RuntimeError should not have been thrown. The same node name can be used in the branch.") + fail("Error! The RuntimeError #{e} should not have been thrown. The same node name can be used in the branch.") end end # Test Addition at a specific position def test_add_at_specific_position - assert(!@root.has_children?, "Should not have any children") + assert(!@root.has_children?, 'Should not have any children') - assert_equal(1, @root.size, "Should have 1 node (the root)") + assert_equal(1, @root.size, 'Should have 1 node (the root)') @root.add(@child1) # First Child added at position 0 # Validate that children = [@child1] assert_equal(@child1, @root[0]) @@ -569,14 +571,14 @@ def test_add_at_specific_position # Validate that children = [@child1, @child2] assert_equal(@child1, @root[0]) assert_equal(@child2, @root[1]) - assert_equal(2, @root.children.size, "Should have two child nodes") + assert_equal(2, @root.children.size, 'Should have two child nodes') @root.add(@child3, 1) # Third child inserted at position 1 (before @child2) # Validate that children = [@child1, @child3, @child2] assert_equal(@child1, @root[0]) assert_equal(@child3, @root[1]) assert_equal(@child2, @root[2]) - assert_equal(3, @root.children.size, "Should have three child nodes") + assert_equal(3, @root.children.size, 'Should have three child nodes') @root.add(@child4, @root.children.size) # Fourth child inserted at the end (equivalent to plain #add(child4) # Validate that children = [@child1, @child3, @child2, @child4] @@ -584,7 +586,7 @@ def test_add_at_specific_position assert_equal(@child3, @root[1]) assert_equal(@child2, @root[2]) assert_equal(@child4, @root[3]) - assert_equal(4, @root.children.size, "Should have four child nodes") + assert_equal(4, @root.children.size, 'Should have four child nodes') # Now, a negative test. We are preventing addition to a position that does not exist. assert_raise(RuntimeError) { @@ -596,7 +598,7 @@ def test_add_at_specific_position assert_equal(@child2, @root[2]) assert_equal(@child4, @root[3]) assert_nil(@root[4]) - assert_equal(4, @root.children.size, "Should have four child nodes") + assert_equal(4, @root.children.size, 'Should have four child nodes') # Another negative test. Lets attempt to add from the end at a position that is not available assert_raise(RuntimeError) { @@ -607,7 +609,7 @@ def test_add_at_specific_position assert_equal(@child3, @root[-3]) assert_equal(@child2, @root[-2]) assert_equal(@child4, @root[-1]) - assert_equal(4, @root.children.size, "Should have four child nodes") + assert_equal(4, @root.children.size, 'Should have four child nodes') # Lets correctly add the fifth child from the end to effectively prepend the node. @root.add(@child5, -(@root.children.size+1)) # Fifth child inserted beyond the first position; i.e. at -5 @@ -617,7 +619,7 @@ def test_add_at_specific_position assert_equal(@child3, @root[-3]) assert_equal(@child2, @root[-2]) assert_equal(@child4, @root[-1]) - assert_equal(5, @root.children.size, "Should have five child nodes") + assert_equal(5, @root.children.size, 'Should have five child nodes') end # Test the replace! and replace_with! methods @@ -626,40 +628,40 @@ def test_replace_bang @root << @child2 @root << @child3 - assert_equal(4, @root.size, "Should have four nodes") - assert(@root.children.include?(@child1), "Should parent child1") - assert(@root.children.include?(@child2), "Should parent child2") - assert(@root.children.include?(@child3), "Should parent child3") - assert(!@root.children.include?(@child4), "Should not parent child4") + assert_equal(4, @root.size, 'Should have four nodes') + assert(@root.children.include?(@child1), 'Should parent child1') + assert(@root.children.include?(@child2), 'Should parent child2') + assert(@root.children.include?(@child3), 'Should parent child3') + assert(!@root.children.include?(@child4), 'Should not parent child4') @root.replace!(@child2, @child4) # Also test replacing with a node of the same name @root.replace! @child4, @child4.detached_copy - assert_equal(4, @root.size, "Should have three nodes") - assert(@root.children.include?(@child1), "Should parent child1") - assert(!@root.children.include?(@child2), "Should not parent child2") - assert(@root.children.include?(@child3), "Should parent child3") - assert(@root.children.include?(@child4), "Should parent child4") - assert_equal(1, @root.children.find_index(@child4), "Should add child4 to index 1") + assert_equal(4, @root.size, 'Should have three nodes') + assert(@root.children.include?(@child1), 'Should parent child1') + assert(!@root.children.include?(@child2), 'Should not parent child2') + assert(@root.children.include?(@child3), 'Should parent child3') + assert(@root.children.include?(@child4), 'Should parent child4') + assert_equal(1, @root.children.find_index(@child4), 'Should add child4 to index 1') end def test_replace_with @root << @child1 @root << @child2 - assert_equal(3, @root.size, "Should have three nodes") - assert(@root.children.include?(@child1), "Should parent child1") - assert(@root.children.include?(@child2), "Should parent child2") - assert(!@root.children.include?(@child3), "Should not parent child3") + assert_equal(3, @root.size, 'Should have three nodes') + assert(@root.children.include?(@child1), 'Should parent child1') + assert(@root.children.include?(@child2), 'Should parent child2') + assert(!@root.children.include?(@child3), 'Should not parent child3') @child2.replace_with @child3 - assert_equal(3, @root.size, "Should have three nodes") - assert(@root.children.include?(@child1), "Should parent child1") - assert(!@root.children.include?(@child2), "Should not parent child2") - assert(@root.children.include?(@child3), "Should parent child3") + assert_equal(3, @root.size, 'Should have three nodes') + assert(@root.children.include?(@child1), 'Should parent child1') + assert(!@root.children.include?(@child2), 'Should not parent child2') + assert(@root.children.include?(@child3), 'Should parent child3') end # Test the remove! and remove_all! methods. @@ -667,57 +669,57 @@ def test_remove_bang @root << @child1 @root << @child2 - assert(@root.has_children?, "Should have children") - assert_equal(3, @root.size, "Should have three nodes") + assert(@root.has_children?, 'Should have children') + assert_equal(3, @root.size, 'Should have three nodes') @root.remove!(@child1) - assert_equal(2, @root.size, "Should have two nodes") + assert_equal(2, @root.size, 'Should have two nodes') @root.remove!(@child2) - assert(!@root.has_children?, "Should have no children") - assert_equal(1, @root.size, "Should have one node") + assert(!@root.has_children?, 'Should have no children') + assert_equal(1, @root.size, 'Should have one node') @root << @child1 @root << @child2 - assert(@root.has_children?, "Should have children") - assert_equal(3, @root.size, "Should have three nodes") + assert(@root.has_children?, 'Should have children') + assert_equal(3, @root.size, 'Should have three nodes') @root.remove_all! - assert(!@root.has_children?, "Should have no children") - assert_equal(1, @root.size, "Should have one node") + assert(!@root.has_children?, 'Should have no children') + assert_equal(1, @root.size, 'Should have one node') # Some negative testing @root.remove!(nil) - assert(!@root.has_children?, "Should have no children") - assert_equal(1, @root.size, "Should have one node") + assert(!@root.has_children?, 'Should have no children') + assert_equal(1, @root.size, 'Should have one node') end # Test the remove_all! method. def test_remove_all_bang setup_test_tree - assert(@root.has_children?, "Should have children") + assert(@root.has_children?, 'Should have children') @root.remove_all! - assert(!@root.has_children?, "Should have no children") - assert_equal(1, @root.size, "Should have one node") + assert(!@root.has_children?, 'Should have no children') + assert_equal(1, @root.size, 'Should have one node') end # Test the remove_from_parent! method. def test_remove_from_parent_bang setup_test_tree - assert(@root.has_children?, "Should have children") - assert(!@root.is_leaf?, "Root is not a leaf here") + assert(@root.has_children?, 'Should have children') + assert(!@root.is_leaf?, 'Root is not a leaf here') child1 = @root[0] - assert_not_nil(child1, "Child 1 should exist") + assert_not_nil(child1, 'Child 1 should exist') assert_same(@root, child1.root, "Child 1's root should be ROOT") - assert(@root.include?(child1), "root should have child1") + assert(@root.include?(child1), 'root should have child1') child1.remove_from_parent! assert_same(child1, child1.root, "Child 1's root should be self") - assert(!@root.include?(child1), "root should not have child1") + assert(!@root.include?(child1), 'root should not have child1') child1.remove_from_parent! assert_same(child1, child1.root, "Child 1's root should still be self") @@ -727,35 +729,35 @@ def test_remove_from_parent_bang def test_children setup_test_tree - assert(@root.has_children?, "Should have children") - assert_equal(5, @root.size, "Should have five nodes") - assert(@child3.has_children?, "Should have children") - assert(!@child3.is_leaf?, "Should not be a leaf") + assert(@root.has_children?, 'Should have children') + assert_equal(5, @root.size, 'Should have five nodes') + assert(@child3.has_children?, 'Should have children') + assert(!@child3.is_leaf?, 'Should not be a leaf') - assert_equal(1, @child3.node_height, "The subtree at Child 3 should have a height of 1") - for child in [@child1, @child2, @child4] + assert_equal(1, @child3.node_height, 'The subtree at Child 3 should have a height of 1') + [@child1, @child2, @child4].each { |child| assert_equal(0, child.node_height, "The subtree at #{child.name} should have a height of 0") - end + } result_array = @root.children - assert_equal(3, result_array.length, "Should have three direct children") - assert(!result_array.include?(@root), "Should not have root") - assert_equal(result_array[0], @child1, "Should have child 1") - assert_equal(result_array[1], @child2, "Should have child 2") - assert_equal(result_array[2], @child3, "Should have child 3") - assert(!result_array.include?(@child4), "Should not have child 4") + assert_equal(3, result_array.length, 'Should have three direct children') + assert(!result_array.include?(@root), 'Should not have root') + assert_equal(result_array[0], @child1, 'Should have child 1') + assert_equal(result_array[1], @child2, 'Should have child 2') + assert_equal(result_array[2], @child3, 'Should have child 3') + assert(!result_array.include?(@child4), 'Should not have child 4') # Lets try the block version of the method. result_array.clear result = @root.children {|child| result_array << child} assert_equal(@root, result) result_array.length - assert_equal(3, result_array.length, "Should have three children") - assert_equal(result_array[0], @child1, "Should have child 1") - assert_equal(result_array[1], @child2, "Should have child 2") - assert_equal(result_array[2], @child3, "Should have child 3") - assert(!result_array.include?(@child4), "Should not have child 4") + assert_equal(3, result_array.length, 'Should have three children') + assert_equal(result_array[0], @child1, 'Should have child 1') + assert_equal(result_array[1], @child2, 'Should have child 2') + assert_equal(result_array[2], @child3, 'Should have child 3') + assert(!result_array.include?(@child4), 'Should not have child 4') end @@ -764,7 +766,7 @@ def test_first_child setup_test_tree assert_equal(@child1, @root.first_child, "Root's first child is Child1") - assert_nil(@child1.first_child, "Child1 does not have any children") + assert_nil(@child1.first_child, 'Child1 does not have any children') assert_equal(@child4, @child3.first_child, "Child3's first child is Child4") end @@ -773,7 +775,7 @@ def test_last_child setup_test_tree assert_equal(@child3, @root.last_child, "Root's last child is Child3") - assert_nil(@child1.last_child, "Child1 does not have any children") + assert_nil(@child1.last_child, 'Child1 does not have any children') assert_equal(@child4, @child3.last_child, "Child3's last child is Child4") end @@ -781,43 +783,43 @@ def test_last_child def test_find setup_test_tree found_node = @root.find { |node| node == @child2} - assert_same(@child2, found_node, "The node should be Child 2") + assert_same(@child2, found_node, 'The node should be Child 2') found_node = @root.find { |node| node == @child4} - assert_same(@child4, found_node, "The node should be Child 4") + assert_same(@child4, found_node, 'The node should be Child 4') - found_node = @root.find { |node| node.name == "Child4" } - assert_same(@child4, found_node, "The node should be Child 4") - found_node = @root.find { |node| node.name == "NOT PRESENT" } - assert_nil(found_node, "The node should not be found") + found_node = @root.find { |node| node.name == 'Child4' } + assert_same(@child4, found_node, 'The node should be Child 4') + found_node = @root.find { |node| node.name == 'NOT PRESENT' } + assert_nil(found_node, 'The node should not be found') end # Test the parentage method. def test_parentage setup_test_tree - assert_nil(@root.parentage, "Root does not have any parentage") - assert_equal([@root], @child1.parentage, "Child1 has Root as its parent") - assert_equal([@child3, @root], @child4.parentage, "Child4 has Child3 and Root as ancestors") + assert_nil(@root.parentage, 'Root does not have any parentage') + assert_equal([@root], @child1.parentage, 'Child1 has Root as its parent') + assert_equal([@child3, @root], @child4.parentage, 'Child4 has Child3 and Root as ancestors') end # Test the each method. def test_each setup_test_tree - assert(@root.has_children?, "Should have children") - assert_equal(5, @root.size, "Should have five nodes") - assert(@child3.has_children?, "Should have children") + assert(@root.has_children?, 'Should have children') + assert_equal(5, @root.size, 'Should have five nodes') + assert(@child3.has_children?, 'Should have children') nodes = [] @root.each { |node| nodes << node } - assert_equal(5, nodes.length, "Should have FIVE NODES") - assert(nodes.include?(@root), "Should have root") - assert(nodes.include?(@child1), "Should have child 1") - assert(nodes.include?(@child2), "Should have child 2") - assert(nodes.include?(@child3), "Should have child 3") - assert(nodes.include?(@child4), "Should have child 4") + assert_equal(5, nodes.length, 'Should have FIVE NODES') + assert(nodes.include?(@root), 'Should have root') + assert(nodes.include?(@child1), 'Should have child 1') + assert(nodes.include?(@child2), 'Should have child 2') + assert(nodes.include?(@child3), 'Should have child 3') + assert(nodes.include?(@child4), 'Should have child 4') end # Test the each_leaf method. @@ -827,23 +829,23 @@ def test_each_leaf result_array = [] result = @root.each_leaf { |node| result_array << node } assert_equal(@root, result) - assert_equal(3, result_array.length, "Should have THREE LEAF NODES") - assert(!result_array.include?(@root), "Should not have root") - assert(result_array.include?(@child1), "Should have child 1") - assert(result_array.include?(@child2), "Should have child 2") - assert(!result_array.include?(@child3), "Should not have child 3") - assert(result_array.include?(@child4), "Should have child 4") + assert_equal(3, result_array.length, 'Should have THREE LEAF NODES') + assert(!result_array.include?(@root), 'Should not have root') + assert(result_array.include?(@child1), 'Should have child 1') + assert(result_array.include?(@child2), 'Should have child 2') + assert(!result_array.include?(@child3), 'Should not have child 3') + assert(result_array.include?(@child4), 'Should have child 4') # Now lets try without the block result_array.clear result_array = @root.each_leaf assert_equal(Array, result_array.class) - assert_equal(3, result_array.length, "Should have THREE LEAF NODES") - assert(!result_array.include?(@root), "Should not have root") - assert(result_array.include?(@child1), "Should have child 1") - assert(result_array.include?(@child2), "Should have child 2") - assert(!result_array.include?(@child3), "Should not have child 3") - assert(result_array.include?(@child4), "Should have child 4") + assert_equal(3, result_array.length, 'Should have THREE LEAF NODES') + assert(!result_array.include?(@root), 'Should not have root') + assert(result_array.include?(@child1), 'Should have child 1') + assert(result_array.include?(@child2), 'Should have child 2') + assert(!result_array.include?(@child3), 'Should not have child 3') + assert(result_array.include?(@child4), 'Should have child 4') end @@ -852,20 +854,20 @@ def test_parent setup_test_tree assert_nil(@root.parent, "Root's parent should be nil") - assert_equal(@root, @child1.parent, "Parent should be root") - assert_equal(@root, @child3.parent, "Parent should be root") - assert_equal(@child3, @child4.parent, "Parent should be child3") - assert_equal(@root, @child4.parent.parent, "Parent should be root") + assert_equal(@root, @child1.parent, 'Parent should be root') + assert_equal(@root, @child3.parent, 'Parent should be root') + assert_equal(@child3, @child4.parent, 'Parent should be child3') + assert_equal(@root, @child4.parent.parent, 'Parent should be root') end # Test the [] method. def test_indexed_access setup_test_tree - assert_equal(@child1, @root[0], "Should be the first child") - assert_equal(@child4, @root[2][0], "Should be the grandchild") - assert_nil(@root["TEST"], "Should be nil") - assert_nil(@root[99], "Should be nil") + assert_equal(@child1, @root[0], 'Should be the first child') + assert_equal(@child4, @root[2][0], 'Should be the grandchild') + assert_nil(@root['TEST'], 'Should be nil') + assert_nil(@root[99], 'Should be nil') assert_raise(ArgumentError) { @root[nil] } end @@ -879,11 +881,11 @@ def test_print_tree # Tests the binary dumping mechanism with an Object content node def test_marshal_dump # Setup Test Data - test_root = Tree::TreeNode.new("ROOT", "Root Node") - test_content = {"KEY1" => "Value1", "KEY2" => "Value2" } - test_child = Tree::TreeNode.new("Child", test_content) - test_content2 = ["AValue1", "AValue2", "AValue3"] - test_grand_child = Tree::TreeNode.new("Grand Child 1", test_content2) + test_root = Tree::TreeNode.new('ROOT', 'Root Node') + test_content = {'KEY1' => 'Value1', 'KEY2' => 'Value2'} + test_child = Tree::TreeNode.new('Child', test_content) + test_content2 = %w(AValue1 AValue2 AValue3) + test_grand_child = Tree::TreeNode.new('Grand Child 1', test_content2) test_root << test_child << test_grand_child # Perform the test operation @@ -891,30 +893,30 @@ def test_marshal_dump new_root = Marshal.load(data) # And unmarshal # Test the root node - assert_equal(test_root.name, new_root.name, "Must identify as ROOT") + assert_equal(test_root.name, new_root.name, 'Must identify as ROOT') assert_equal(test_root.content, new_root.content, "Must have root's content") - assert(new_root.is_root?, "Must be the ROOT node") - assert(new_root.has_children?, "Must have a child node") + assert(new_root.is_root?, 'Must be the ROOT node') + assert(new_root.has_children?, 'Must have a child node') # Test the child node new_child = new_root[test_child.name] - assert_equal(test_child.name, new_child.name, "Must have child 1") - assert(new_child.has_content?, "Child must have content") - assert(new_child.is_only_child?, "Child must be the only child") + assert_equal(test_child.name, new_child.name, 'Must have child 1') + assert(new_child.has_content?, 'Child must have content') + assert(new_child.is_only_child?, 'Child must be the only child') new_child_content = new_child.content assert_equal(Hash, new_child_content.class, "Class of child's content should be a hash") - assert_equal(test_child.content.size, new_child_content.size, "The content should have same size") + assert_equal(test_child.content.size, new_child_content.size, 'The content should have same size') # Test the grand-child node new_grand_child = new_child[test_grand_child.name] - assert_equal(test_grand_child.name, new_grand_child.name, "Must have grand child") - assert(new_grand_child.has_content?, "Grand-child must have content") - assert(new_grand_child.is_only_child?, "Grand-child must be the only child") + assert_equal(test_grand_child.name, new_grand_child.name, 'Must have grand child') + assert(new_grand_child.has_content?, 'Grand-child must have content') + assert(new_grand_child.is_only_child?, 'Grand-child must be the only child') new_grand_child_content = new_grand_child.content assert_equal(Array, new_grand_child_content.class, "Class of grand-child's content should be an Array") - assert_equal(test_grand_child.content.size, new_grand_child_content.size, "The content should have same size") + assert_equal(test_grand_child.content.size, new_grand_child_content.size, 'The content should have same size') end # marshal_load and marshal_dump are symmetric methods @@ -925,31 +927,33 @@ def test_marshal_dump def test_collect setup_test_tree collect_array = @root.collect do |node| - node.content = "abc" + node.content = 'abc' node end - collect_array.each {|node| assert_equal("abc", node.content, "Should be 'abc'")} + collect_array.each {|node| assert_equal('abc', node.content, "Should be 'abc'")} end # Test freezing the tree def test_freeze_tree_bang setup_test_tree - @root.content = "ABC" - assert_equal("ABC", @root.content, "Content should be 'ABC'") + @root.content = 'ABC' + assert_equal('ABC', @root.content, "Content should be 'ABC'") @root.freeze_tree! # Note: The error raised here depends on the Ruby version. # For Ruby > 1.9, RuntimeError is raised # For Ruby ~ 1.8, TypeError is raised - assert_raise(RuntimeError, TypeError) {@root.content = "123"} - assert_raise(RuntimeError, TypeError) {@root[0].content = "123"} + assert_raise(RuntimeError, TypeError) {@root.content = '123' + } + assert_raise(RuntimeError, TypeError) {@root[0].content = '123' + } end - # Test whether the content is accesible + # Test whether the content is accessible def test_content - pers = Person::new("John", "Doe") - @root.content = pers - assert_same(pers, @root.content, "Content should be the same") + person = Person::new('John', 'Doe') + @root.content = person + assert_same(person, @root.content, 'Content should be the same') end # Test the depth computation algorithm. Note that this is an incorrect computation and actually returns height+1 @@ -957,9 +961,9 @@ def test_content def test_depth begin require 'structured_warnings' - assert_warn(DeprecatedMethodWarning) { do_deprecated_depth } + assert_warn(StructuredWarnings::DeprecatedMethodWarning) { do_deprecated_depth } rescue LoadError - # Since the structued_warnings package is not present, we revert to good old Kernel#warn behavior. + # Since the structured_warnings package is not present, we revert to good old Kernel#warn behavior. do_deprecated_depth end end @@ -969,17 +973,17 @@ def do_deprecated_depth assert_equal(1, @root.depth, "A single node's depth is 1") @root << @child1 - assert_equal(2, @root.depth, "This should be of depth 2") + assert_equal(2, @root.depth, 'This should be of depth 2') @root << @child2 - assert_equal(2, @root.depth, "This should be of depth 2") + assert_equal(2, @root.depth, 'This should be of depth 2') @child2 << @child3 - assert_equal(3, @root.depth, "This should be of depth 3") - assert_equal(2, @child2.depth, "This should be of depth 2") + assert_equal(3, @root.depth, 'This should be of depth 3') + assert_equal(2, @child2.depth, 'This should be of depth 2') @child3 << @child4 - assert_equal(4, @root.depth, "This should be of depth 4") + assert_equal(4, @root.depth, 'This should be of depth 4') end # Test the height computation algorithm @@ -987,23 +991,23 @@ def test_node_height assert_equal(0, @root.node_height, "A single node's height is 0") @root << @child1 - assert_equal(1, @root.node_height, "This should be of height 1") - assert_equal(0, @child1.node_height, "This should be of height 0") + assert_equal(1, @root.node_height, 'This should be of height 1') + assert_equal(0, @child1.node_height, 'This should be of height 0') @root << @child2 - assert_equal(1, @root.node_height, "This should be of height 1") - assert_equal(0, @child2.node_height, "This should be of height 0") + assert_equal(1, @root.node_height, 'This should be of height 1') + assert_equal(0, @child2.node_height, 'This should be of height 0') @child2 << @child3 - assert_equal(2, @root.node_height, "This should be of height 2") - assert_equal(1, @child2.node_height, "This should be of height 1") - assert_equal(0, @child3.node_height, "This should be of height 0") + assert_equal(2, @root.node_height, 'This should be of height 2') + assert_equal(1, @child2.node_height, 'This should be of height 1') + assert_equal(0, @child3.node_height, 'This should be of height 0') @child3 << @child4 - assert_equal(3, @root.node_height, "This should be of height 3") - assert_equal(2, @child2.node_height, "This should be of height 2") - assert_equal(1, @child3.node_height, "This should be of height 1") - assert_equal(0, @child4.node_height, "This should be of height 0") + assert_equal(3, @root.node_height, 'This should be of height 3') + assert_equal(2, @child2.node_height, 'This should be of height 2') + assert_equal(1, @child3.node_height, 'This should be of height 1') + assert_equal(0, @child4.node_height, 'This should be of height 0') end # Test the depth computation algorithm. Note that this is the correct depth computation. The original @@ -1013,29 +1017,29 @@ def test_node_depth setup_test_tree - for child in [@child1, @child2, @child3] + [@child1, @child2, @child3].each { |child| assert_equal(1, child.node_depth, "Node #{child.name} should have depth 1") - end + } - assert_equal(2, @child4.node_depth, "Child 4 should have depth 2") + assert_equal(2, @child4.node_depth, 'Child 4 should have depth 2') @root << @child5 << @child3 - assert_equal(3, @child4.node_depth, "Child 4 should have depth 3 after Child 5 inserted above") + assert_equal(3, @child4.node_depth, 'Child 4 should have depth 3 after Child 5 inserted above') end # Test the level method. Since this is an alias of node_depth, we just test for equivalence def test_level assert_equal(0, @root.level, "A root node's level is 0") - assert_equal(@root.node_depth, @root.level, "Level and depth should be the same") + assert_equal(@root.node_depth, @root.level, 'Level and depth should be the same') setup_test_tree - for child in [@child1, @child2, @child3] + [@child1, @child2, @child3].each { |child| assert_equal(1, child.level, "Node #{child.name} should have level 1") - assert_equal(@root.node_depth, @root.level, "Level and depth should be the same") - end + assert_equal(@root.node_depth, @root.level, 'Level and depth should be the same') + } - assert_equal(2, @child4.level, "Child 4 should have level 2") + assert_equal(2, @child4.level, 'Child 4 should have level 2') end # Test the breadth computation algorithm @@ -1043,29 +1047,29 @@ def test_breadth assert_equal(1, @root.breadth, "A single node's breadth is 1") @root << @child1 - assert_equal(1, @root.breadth, "This should be of breadth 1") + assert_equal(1, @root.breadth, 'This should be of breadth 1') @root << @child2 - assert_equal(2, @child1.breadth, "This should be of breadth 2") - assert_equal(2, @child2.breadth, "This should be of breadth 2") + assert_equal(2, @child1.breadth, 'This should be of breadth 2') + assert_equal(2, @child2.breadth, 'This should be of breadth 2') @root << @child3 - assert_equal(3, @child1.breadth, "This should be of breadth 3") - assert_equal(3, @child2.breadth, "This should be of breadth 3") + assert_equal(3, @child1.breadth, 'This should be of breadth 3') + assert_equal(3, @child2.breadth, 'This should be of breadth 3') @child3 << @child4 - assert_equal(1, @child4.breadth, "This should be of breadth 1") + assert_equal(1, @child4.breadth, 'This should be of breadth 1') end # Test the breadth for each def test_breadth_each - j = Tree::TreeNode.new("j") - f = Tree::TreeNode.new("f") - k = Tree::TreeNode.new("k") - a = Tree::TreeNode.new("a") - d = Tree::TreeNode.new("d") - h = Tree::TreeNode.new("h") - z = Tree::TreeNode.new("z") + j = Tree::TreeNode.new('j') + f = Tree::TreeNode.new('f') + k = Tree::TreeNode.new('k') + a = Tree::TreeNode.new('a') + d = Tree::TreeNode.new('d') + h = Tree::TreeNode.new('h') + z = Tree::TreeNode.new('z') # The expected order of response expected_array = [j, @@ -1108,13 +1112,13 @@ def test_breadth_each # Test the preordered_each method. def test_preordered_each - j = Tree::TreeNode.new("j") - f = Tree::TreeNode.new("f") - k = Tree::TreeNode.new("k") - a = Tree::TreeNode.new("a") - d = Tree::TreeNode.new("d") - h = Tree::TreeNode.new("h") - z = Tree::TreeNode.new("z") + j = Tree::TreeNode.new('j') + f = Tree::TreeNode.new('f') + k = Tree::TreeNode.new('k') + a = Tree::TreeNode.new('a') + d = Tree::TreeNode.new('d') + h = Tree::TreeNode.new('h') + z = Tree::TreeNode.new('z') # The expected order of response expected_array = [j, f, a, d, h, k, z] @@ -1147,13 +1151,13 @@ def test_preordered_each # Test the postordered_each method. def test_postordered_each - j = Tree::TreeNode.new("j") - f = Tree::TreeNode.new("f") - k = Tree::TreeNode.new("k") - a = Tree::TreeNode.new("a") - d = Tree::TreeNode.new("d") - h = Tree::TreeNode.new("h") - z = Tree::TreeNode.new("z") + j = Tree::TreeNode.new('j') + f = Tree::TreeNode.new('f') + k = Tree::TreeNode.new('k') + a = Tree::TreeNode.new('a') + d = Tree::TreeNode.new('d') + h = Tree::TreeNode.new('h') + z = Tree::TreeNode.new('z') # The expected order of response expected_array = [d, a, h, f, z, k, j] @@ -1198,14 +1202,14 @@ def test_postordered_each def test_detached_copy setup_test_tree - assert(@root.has_children?, "The root should have children") + assert(@root.has_children?, 'The root should have children') copy_of_root = @root.detached_copy - assert(!copy_of_root.has_children?, "The copy should not have children") - assert_equal(@root.name, copy_of_root.name, "The names should be equal") + assert(!copy_of_root.has_children?, 'The copy should not have children') + assert_equal(@root.name, copy_of_root.name, 'The names should be equal') # Try the same test with a child node - assert(!@child3.is_root?, "Child 3 is not a root") - assert(@child3.has_children?, "Child 3 has children") + assert(!@child3.is_root?, 'Child 3 is not a root') + assert(@child3.has_children?, 'Child 3 has children') copy_of_child3 = @child3.detached_copy assert(copy_of_child3.is_root?, "Child 3's copy is a root") assert(!copy_of_child3.has_children?, "Child 3's copy does not have children") @@ -1215,61 +1219,61 @@ def test_detached_copy def test_detached_subtree_copy setup_test_tree - assert(@root.has_children?, "The root should have children.") + assert(@root.has_children?, 'The root should have children.') tree_copy = @root.detached_subtree_copy - assert_equal(@root.name, tree_copy.name, "The names should be equal.") - assert_not_equal(@root.object_id, tree_copy.object_id, "Object_ids should differ.") - assert(tree_copy.is_root?, "Copied root should be a root node.") - assert(tree_copy.has_children?, "Copied tree should have children.") - assert_equal(tree_copy.children.count, @root.children.count, "Copied tree and the original tree should have same number of children.") + assert_equal(@root.name, tree_copy.name, 'The names should be equal.') + assert_not_equal(@root.object_id, tree_copy.object_id, 'Object_ids should differ.') + assert(tree_copy.is_root?, 'Copied root should be a root node.') + assert(tree_copy.has_children?, 'Copied tree should have children.') + assert_equal(tree_copy.children.count, @root.children.count, 'Copied tree and the original tree should have same number of children.') - assert_equal(tree_copy[0].name, @child1.name, "The names of Child1 (original and copy) should be same.") - assert_not_equal(tree_copy[0].object_id, @child1.object_id, "Child1 Object_ids (original and copy) should differ.") - assert(!tree_copy[0].is_root?, "Child1 copied should not be root.") - assert(!tree_copy[0].has_children?, "Child1 copied should not have children.") + assert_equal(tree_copy[0].name, @child1.name, 'The names of Child1 (original and copy) should be same.') + assert_not_equal(tree_copy[0].object_id, @child1.object_id, 'Child1 Object_ids (original and copy) should differ.') + assert(!tree_copy[0].is_root?, 'Child1 copied should not be root.') + assert(!tree_copy[0].has_children?, 'Child1 copied should not have children.') - assert_equal(tree_copy[1].name, @child2.name, "The names of Child2 (original and copy) should be same.") - assert_not_equal(tree_copy[1].object_id, @child2.object_id, "Child2 Object_ids (original and copy) should differ.") - assert(!tree_copy[1].is_root?, "Child2 copied should not be root.") - assert(!tree_copy[1].has_children?, "Child2 copied should not have children.") + assert_equal(tree_copy[1].name, @child2.name, 'The names of Child2 (original and copy) should be same.') + assert_not_equal(tree_copy[1].object_id, @child2.object_id, 'Child2 Object_ids (original and copy) should differ.') + assert(!tree_copy[1].is_root?, 'Child2 copied should not be root.') + assert(!tree_copy[1].has_children?, 'Child2 copied should not have children.') - assert_equal(tree_copy[2].name, @child3.name, "The names of Child3 (original and copy) should be same.") - assert_not_equal(tree_copy[2].object_id, @child3.object_id, "Child3 Object_ids (original and copy) should differ.") - assert(!tree_copy[2].is_root?, "Child3 copied should not be root.") - assert(tree_copy[2].has_children?, "Child3 copied should have children.") + assert_equal(tree_copy[2].name, @child3.name, 'The names of Child3 (original and copy) should be same.') + assert_not_equal(tree_copy[2].object_id, @child3.object_id, 'Child3 Object_ids (original and copy) should differ.') + assert(!tree_copy[2].is_root?, 'Child3 copied should not be root.') + assert(tree_copy[2].has_children?, 'Child3 copied should have children.') - assert_equal(tree_copy[2][0].name, @child4.name, "The names of Child4 (original and copy) should be same.") - assert_not_equal(tree_copy[2][0].object_id, @child4.object_id, "Child4 Object_ids (original and copy) should differ.") - assert(!tree_copy[2][0].is_root?, "Child4 copied should not be root.") - assert(!tree_copy[2][0].has_children?, "Child4 copied should not have children.") + assert_equal(tree_copy[2][0].name, @child4.name, 'The names of Child4 (original and copy) should be same.') + assert_not_equal(tree_copy[2][0].object_id, @child4.object_id, 'Child4 Object_ids (original and copy) should differ.') + assert(!tree_copy[2][0].is_root?, 'Child4 copied should not be root.') + assert(!tree_copy[2][0].has_children?, 'Child4 copied should not have children.') end # Test the has_children? method. def test_has_children_eh setup_test_tree - assert(@root.has_children?, "The Root node MUST have children") + assert(@root.has_children?, 'The Root node MUST have children') end # test the is_leaf? method. def test_is_leaf_eh setup_test_tree - assert(!@child3.is_leaf?, "Child 3 is not a leaf node") - assert(@child4.is_leaf?, "Child 4 is a leaf node") + assert(!@child3.is_leaf?, 'Child 3 is not a leaf node') + assert(@child4.is_leaf?, 'Child 4 is a leaf node') end # Test the is_root? method. def test_is_root_eh setup_test_tree - assert(@root.is_root?, "The ROOT node must respond as the root node") + assert(@root.is_root?, 'The ROOT node must respond as the root node') end # Test the content= method. def test_content_equals @root.content = nil assert_nil(@root.content, "Root's content should be nil") - @root.content = "ABCD" - assert_equal("ABCD", @root.content, "Root's content should now be 'ABCD'") + @root.content = 'dummy content' + assert_equal('dummy content', @root.content, "Root's content should now be 'dummy content'") end # Test the size method. @@ -1286,10 +1290,10 @@ def test_lt2 # Test the << method @root << @child1 @root << @child2 @root << @child3 << @child4 - assert_not_nil(@root['Child1'], "Child 1 should have been added to Root") - assert_not_nil(@root['Child2'], "Child 2 should have been added to Root") - assert_not_nil(@root['Child3'], "Child 3 should have been added to Root") - assert_not_nil(@child3['Child4'], "Child 4 should have been added to Child3") + assert_not_nil(@root['Child1'], 'Child 1 should have been added to Root') + assert_not_nil(@root['Child2'], 'Child 2 should have been added to Root') + assert_not_nil(@root['Child3'], 'Child 3 should have been added to Root') + assert_not_nil(@child3['Child4'], 'Child 4 should have been added to Child3') end # Test the [] method. @@ -1298,19 +1302,19 @@ def test_index # Test the [] method @root << @child1 @root << @child2 - assert_equal(@child1.name, @root['Child1'].name, "Child 1 should be returned") - assert_equal(@child1.name, @root[0].name, "Child 1 should be returned") - assert_equal(@child1.name, @root[-2].name, "Child 1 should be returned") # Negative access also works - assert_equal(@child1.name, @root[-(@root.children.size)].name, "Child 1 should be returned") # Negative access also works + assert_equal(@child1.name, @root['Child1'].name, 'Child 1 should be returned') + assert_equal(@child1.name, @root[0].name, 'Child 1 should be returned') + assert_equal(@child1.name, @root[-2].name, 'Child 1 should be returned') # Negative access also works + assert_equal(@child1.name, @root[-(@root.children.size)].name, 'Child 1 should be returned') # Negative access also works - assert_equal(@child2.name, @root['Child2'].name, "Child 2 should be returned") - assert_equal(@child2.name, @root[1].name, "Child 2 should be returned") - assert_equal(@child2.name, @root[-1].name, "Child 2 should be returned") # Negative access also works + assert_equal(@child2.name, @root['Child2'].name, 'Child 2 should be returned') + assert_equal(@child2.name, @root[1].name, 'Child 2 should be returned') + assert_equal(@child2.name, @root[-1].name, 'Child 2 should be returned') # Negative access also works - assert_nil(@root['Some Random Name'], "Should return nil") - assert_nil(@root[99], "Should return nil") - assert_nil(@root[-(@root.children.size+1)], "Should return nil") - assert_nil(@root[-3], "Should return nil") + assert_nil(@root['Some Random Name'], 'Should return nil') + assert_nil(@root[99], 'Should return nil') + assert_nil(@root[-(@root.children.size+1)], 'Should return nil') + assert_nil(@root[-3], 'Should return nil') end # Test the in_degree method. @@ -1340,18 +1344,18 @@ def test_json_serialization setup_test_tree expected_json = { - "name" => "ROOT", - "content" => "Root Node", - JSON.create_id => "Tree::TreeNode", - "children" => [ - {"name" => "Child1", "content" => "Child Node 1", JSON.create_id => "Tree::TreeNode"}, - {"name" => "Child2", "content" => "Child Node 2", JSON.create_id => "Tree::TreeNode"}, + 'name' => 'ROOT', + 'content' => 'Root Node', + JSON.create_id => 'Tree::TreeNode', + 'children' => [ + {'name' => 'Child1', 'content' => 'Child Node 1', JSON.create_id => 'Tree::TreeNode'}, + {'name' => 'Child2', 'content' => 'Child Node 2', JSON.create_id => 'Tree::TreeNode'}, { - "name" => "Child3", - "content" => "Child Node 3", - JSON.create_id => "Tree::TreeNode", - "children" => [ - {"name" => "Child4", "content" => "Grand Child 1", JSON.create_id => "Tree::TreeNode"} + 'name' => 'Child3', + 'content' => 'Child Node 3', + JSON.create_id => 'Tree::TreeNode', + 'children' => [ + {'name' => 'Child4', 'content' => 'Grand Child 1', JSON.create_id => 'Tree::TreeNode'} ] } ] @@ -1362,18 +1366,18 @@ def test_json_serialization def test_json_deserialization tree_as_json = { - "name" => "ROOT", - "content" => "Root Node", - JSON.create_id => "Tree::TreeNode", - "children" => [ - {"name" => "Child1", "content" => "Child Node 1", JSON.create_id => "Tree::TreeNode"}, - {"name" => "Child2", "content" => "Child Node 2", JSON.create_id => "Tree::TreeNode"}, + 'name' => 'ROOT', + 'content' => 'Root Node', + JSON.create_id => 'Tree::TreeNode', + 'children' => [ + {'name' => 'Child1', 'content' => 'Child Node 1', JSON.create_id => 'Tree::TreeNode'}, + {'name' => 'Child2', 'content' => 'Child Node 2', JSON.create_id => 'Tree::TreeNode'}, { - "name" => "Child3", - "content" => "Child Node 3", - JSON.create_id => "Tree::TreeNode", - "children" => [ - {"name" => "Child4", "content" => "Grand Child 1", JSON.create_id => "Tree::TreeNode"} + 'name' => 'Child3', + 'content' => 'Child Node 3', + JSON.create_id => 'Tree::TreeNode', + 'children' => [ + {'name' => 'Child4', 'content' => 'Grand Child 1', JSON.create_id => 'Tree::TreeNode'} ] } ] @@ -1381,30 +1385,30 @@ def test_json_deserialization tree = JSON.parse(tree_as_json, :create_additions => true) - assert_equal(@root.name, tree.root.name, "Root should be returned") - assert_equal(@child1.name, tree[0].name, "Child 1 should be returned") - assert_equal(@child2.name, tree[1].name, "Child 2 should be returned") - assert_equal(@child3.name, tree[2].name, "Child 3 should be returned") - assert_equal(@child4.name, tree[2][0].name, "Grand Child 1 should be returned") + assert_equal(@root.name, tree.root.name, 'Root should be returned') + assert_equal(@child1.name, tree[0].name, 'Child 1 should be returned') + assert_equal(@child2.name, tree[1].name, 'Child 2 should be returned') + assert_equal(@child3.name, tree[2].name, 'Child 3 should be returned') + assert_equal(@child4.name, tree[2][0].name, 'Grand Child 1 should be returned') end - def test_json_roundtrip - root_node = Tree::TreeNode.new("RTROOT", "Root Content") - root_node << Tree::TreeNode.new("RTCHILD1", "Child1 Content") << Tree::TreeNode.new("RTGRANDCHILD1", "GrandChild1 Content") - root_node << Tree::TreeNode.new("RTCHILD2", "Child2 Content") + def test_json_round_trip + root_node = Tree::TreeNode.new('ROOT', 'Root Content') + root_node << Tree::TreeNode.new('CHILD1', 'Child1 Content') << Tree::TreeNode.new('GRAND_CHILD1', 'GrandChild1 Content') + root_node << Tree::TreeNode.new('CHILD2', 'Child2 Content') j = root_node.to_json k = JSON.parse(j, :create_additions => true) - assert_equal(k.name, root_node.name, "Root should be returned") - assert_equal(k[0].name, root_node[0].name, "Child 1 should be returned") - assert_equal(k[0][0].name, root_node[0][0].name, "Grand Child 1 should be returned") - assert_equal(k[1].name, root_node[1].name, "Child 2 should be returned") + assert_equal(k.name, root_node.name, 'Root should be returned') + assert_equal(k[0].name, root_node[0].name, 'Child 1 should be returned') + assert_equal(k[0][0].name, root_node[0][0].name, 'Grand Child 1 should be returned') + assert_equal(k[1].name, root_node[1].name, 'Child 2 should be returned') end # Test the old CamelCase method names - def test_old_camelCase_method_names + def test_old_camel_case_names setup_test_tree meth_names_to_test = %w{isRoot? isLeaf? hasContent? @@ -1415,19 +1419,20 @@ def test_old_camelCase_method_names require 'structured_warnings' - DeprecatedMethodWarning.disable do + StructuredWarnings::DeprecatedMethodWarning.disable do + # noinspection RubyResolve assert(@root.isRoot?) # Test if the original method is really called end meth_names_to_test.each do |meth_name| - assert_warn(DeprecatedMethodWarning) {@root.send(meth_name)} + assert_warn(StructuredWarnings::DeprecatedMethodWarning) {@root.send(meth_name)} end # Special Case for printTree to avoid putting stuff on the STDOUT during the unit test. begin require 'stringio' $stdout = StringIO.new - assert_warn(DeprecatedMethodWarning) { @root.send('printTree') } + assert_warn(StructuredWarnings::DeprecatedMethodWarning) { @root.send('printTree') } ensure $stdout = STDOUT end @@ -1438,11 +1443,11 @@ def test_old_camelCase_method_names def test_integer_node_names require 'structured_warnings' - assert_warn(StandardWarning) do - @n_root = Tree::TreeNode.new(0, "Root Node") - @n_child1 = Tree::TreeNode.new(1, "Child Node 1") - @n_child2 = Tree::TreeNode.new(2, "Child Node 2") - @n_child3 = Tree::TreeNode.new("three", "Child Node 3") + assert_warn(StructuredWarnings::StandardWarning) do + @n_root = Tree::TreeNode.new(0, 'Root Node') + @n_child1 = Tree::TreeNode.new(1, 'Child Node 1') + @n_child2 = Tree::TreeNode.new(2, 'Child Node 2') + @n_child3 = Tree::TreeNode.new('three', 'Child Node 3') end @n_root << @n_child1 @@ -1455,25 +1460,25 @@ def test_integer_node_names assert_equal(@n_root[1, true].name, 1) # This will work, as the flag is now enabled # Sanity check for the "normal" string name cases. Both cases should work. - assert_equal(@n_root["three", false].name, "three") + assert_equal(@n_root['three', false].name, 'three') - StandardWarning.disable - assert_equal(@n_root["three", true].name, "three") + StructuredWarnings::StandardWarning.disable + assert_equal(@n_root['three', true].name, 'three') # Also ensure that the warning is actually being thrown - StandardWarning.enable - assert_warn(StandardWarning) {assert_equal(@n_root["three", true].name, "three") } + StructuredWarnings::StandardWarning.enable + assert_warn(StructuredWarnings::StandardWarning) {assert_equal(@n_root['three', true].name, 'three') } end # Test the addition of a node to itself as a child def test_add_node_to_self_as_child - root = Tree::TreeNode.new("root") + root = Tree::TreeNode.new('root') # Lets check the direct parentage scenario assert_raise(ArgumentError) {root << root} # And now a scenario where the node addition is done down the hierarchy - child = Tree::TreeNode.new("child") + child = Tree::TreeNode.new('child') assert_raise(ArgumentError) { root << child << root } end @@ -1484,7 +1489,8 @@ def test_single_node_becomes_leaf leafs = @root.each_leaf parents = leafs.collect {|leaf| leaf.parent } leafs.each {|leaf| leaf.remove_from_parent!} - parents.each {|parent| assert(parent.is_leaf?) if not parent.has_children?} + parents.each {|parent| assert(parent.is_leaf?) unless parent.has_children? + } end @@ -1498,7 +1504,7 @@ def test_unique_node_names begin @root.first_child << @child2 rescue RuntimeError => e - fail("No error should have been raised for adding a non-sibling duplicate.") + fail("No error #{e} should have been raised for adding a non-sibling duplicate.") end end @@ -1520,15 +1526,15 @@ def setup_other_test_tree # @other_tree = @root.detached_copy @other_tree << @child1.detached_copy - @other_tree["Child1"] << Tree::TreeNode.new("Child1a", "GrandChild Node 1a") - @other_tree["Child1"] << Tree::TreeNode.new("Child1b", "GrandChild Node 1b") + @other_tree['Child1'] << Tree::TreeNode.new('Child1a', 'GrandChild Node 1a') + @other_tree['Child1'] << Tree::TreeNode.new('Child1b', 'GrandChild Node 1b') @other_tree << @child3.detached_copy - @other_tree["Child3"] << Tree::TreeNode.new("Child3a", "GrandChild Node 3a") - @other_tree["Child3"]["Child3a"] << Tree::TreeNode.new("Child3a1", "GreatGrandChild Node 3a1") + @other_tree['Child3'] << Tree::TreeNode.new('Child3a', 'GrandChild Node 3a') + @other_tree['Child3']['Child3a'] << Tree::TreeNode.new('Child3a1', 'GreatGrandChild Node 3a1') # And another (different) one so we can test exceptions... - @other_tree2 = Tree::TreeNode.new("ROOTIE", "A different root") - @other_tree2 << Tree::TreeNode.new("new_child1", "New Child 1") + @other_tree2 = Tree::TreeNode.new('ROOT2', 'A different root') + @other_tree2 << Tree::TreeNode.new('new_child1', 'New Child 1') end # Test tree merging. @@ -1538,23 +1544,17 @@ def test_merge merged_tree = @root.merge(@other_tree) - # puts "\n\ntest_merge:\n\n" - # @root.print_tree - # puts "\n" - # @other_tree.print_tree - # puts "\n" - # merged_tree.print_tree - assert( @root["Child1"]["Child1a"].nil?, ".merge() has altered self." ) - assert( @root["Child1"]["Child1b"].nil?, ".merge() has altered self." ) - assert( @root["Child3"]["Child3a"].nil?, ".merge() has altered self." ) + assert(@root['Child1']['Child1a'].nil?, '.merge() has altered self.') + assert(@root['Child1']['Child1b'].nil?, '.merge() has altered self.') + assert(@root['Child3']['Child3a'].nil?, '.merge() has altered self.') assert( merged_tree.is_a?(Tree::TreeNode) ) - assert( !merged_tree["Child1"]["Child1a"].nil?, ".merge() has not included ['Child1']['Child1a'] from other_tree." ) - assert( !merged_tree["Child1"]["Child1b"].nil?, ".merge() has not included ['Child1']['Child1b'] from other_tree." ) - assert( !merged_tree["Child3"]["Child3a"].nil?, ".merge() has not included ['Child3']['Child3a'] from other_tree." ) - assert( !merged_tree["Child2"].nil?, ".merge() has not included ['Child2'] from self." ) - assert( !merged_tree["Child3"]["Child3a"]["Child3a1"].nil?, ".merge() has not included ['Child3']['Child3a']['Child3a1'] from other_tree." ) - assert( !merged_tree["Child3"]["Child4"].nil?, ".merge() has not included ['Child3']['Child4'] from self." ) + assert(!merged_tree['Child1']['Child1a'].nil?, ".merge() has not included ['Child1']['Child1a'] from other_tree." ) + assert(!merged_tree['Child1']['Child1b'].nil?, ".merge() has not included ['Child1']['Child1b'] from other_tree." ) + assert(!merged_tree['Child3']['Child3a'].nil?, ".merge() has not included ['Child3']['Child3a'] from other_tree." ) + assert(!merged_tree['Child2'].nil?, ".merge() has not included ['Child2'] from self." ) + assert(!merged_tree['Child3']['Child3a']['Child3a1'].nil?, ".merge() has not included ['Child3']['Child3a']['Child3a1'] from other_tree." ) + assert(!merged_tree['Child3']['Child4'].nil?, ".merge() has not included ['Child3']['Child4'] from self." ) assert_raise(ArgumentError) { @root.merge(@other_tree2) } assert_raise(TypeError) { @root.merge('ROOT') } @@ -1565,22 +1565,17 @@ def test_merge_bang setup_test_tree setup_other_test_tree - # puts "\n\ntest_merge_bang:\n\n" - # @root.print_tree - # puts "\n" - # @other_tree.print_tree - - @root.merge!(@other_tree) + @root.merge!(@other_tree) # puts "\n" # @root.print_tree - assert( !@root["Child1"]["Child1a"].nil?, ".merge() has not included ['Child1']['Child1a'] from other_tree." ) - assert( !@root["Child1"]["Child1b"].nil?, ".merge() has not included ['Child1']['Child1b'] from other_tree." ) - assert( !@root["Child3"]["Child3a"].nil?, ".merge() has not included ['Child3']['Child3a'] from other_tree." ) - assert( !@root["Child2"].nil?, ".merge() has not included ['Child2'] from self." ) - assert( !@root["Child3"]["Child3a"]["Child3a1"].nil?, ".merge() has not included ['Child3']['Child3a']['Child3a1'] from other_tree." ) - assert( !@root["Child3"]["Child4"].nil?, ".merge() has not included ['Child3']['Child4'] from self." ) + assert(!@root['Child1']['Child1a'].nil?, ".merge() has not included ['Child1']['Child1a'] from other_tree." ) + assert(!@root['Child1']['Child1b'].nil?, ".merge() has not included ['Child1']['Child1b'] from other_tree." ) + assert(!@root['Child3']['Child3a'].nil?, ".merge() has not included ['Child3']['Child3a'] from other_tree." ) + assert(!@root['Child2'].nil?, ".merge() has not included ['Child2'] from self." ) + assert(!@root['Child3']['Child3a']['Child3a1'].nil?, ".merge() has not included ['Child3']['Child3a']['Child3a1'] from other_tree." ) + assert(!@root['Child3']['Child4'].nil?, ".merge() has not included ['Child3']['Child4'] from self." ) assert_raise(ArgumentError) { @root.merge!(@other_tree2) } assert_raise(TypeError) { @root.merge!('ROOT') } @@ -1616,38 +1611,38 @@ def test_rename_child end def test_change_parent - root_node = Tree::TreeNode.new("OLDROOT") + root_node = Tree::TreeNode.new('OLD_ROOT') - child_node = Tree::TreeNode.new("CHILD") + child_node = Tree::TreeNode.new('CHILD') assert_equal(0, child_node.node_depth) root_node << child_node - assert_equal(root_node["CHILD"].name, "CHILD") + assert_equal(root_node['CHILD'].name, 'CHILD') assert_equal(0, root_node.node_depth) assert_equal(1, child_node.node_depth) - grandchild_node = Tree::TreeNode.new("GRANDCHILD") + grandchild_node = Tree::TreeNode.new('GRANDCHILD') child_node << grandchild_node - assert_equal(root_node["CHILD"]["GRANDCHILD"].name, "GRANDCHILD") + assert_equal(root_node['CHILD']['GRANDCHILD'].name, 'GRANDCHILD') assert_equal(0, root_node.node_depth) assert_equal(1, child_node.node_depth) assert_equal(2, grandchild_node.node_depth) - root2_node = Tree::TreeNode.new("NEWROOT") + root2_node = Tree::TreeNode.new('NEW_ROOT') assert_equal(0, root2_node.node_depth) # Move the grand child to a new root. root2_node << grandchild_node - assert_equal(root2_node["GRANDCHILD"].name, "GRANDCHILD") + assert_equal(root2_node['GRANDCHILD'].name, 'GRANDCHILD') assert_equal(root2_node, grandchild_node.parent) assert_equal(1, grandchild_node.node_depth) # Test the move semantics for addition of an existing child node - root1 = Tree::TreeNode.new("1") - root1 << Tree::TreeNode.new("2") << Tree::TreeNode.new("4") - root1 << Tree::TreeNode.new("3") << Tree::TreeNode.new("5") - root1["3"] << Tree::TreeNode.new("6") - assert_equal(root1["3"]["6"].name, "6") + root1 = Tree::TreeNode.new('1') + root1 << Tree::TreeNode.new('2') << Tree::TreeNode.new('4') + root1 << Tree::TreeNode.new('3') << Tree::TreeNode.new('5') + root1['3'] << Tree::TreeNode.new('6') + assert_equal(root1['3']['6'].name, '6') # Create a new tree root2 = root1.dup @@ -1655,24 +1650,24 @@ def test_change_parent assert_not_same(root1, root2) # Now 'move' the "4" node to the new tree. This should have 'dup' semantics. - root2["3"] << root1["2"]["4"] - assert_equal("3", root2["3"]["4"].parent.name) # This is on the new tree - assert_nil(root1["2"]["4"]) # This is on the old tree + root2['3'] << root1['2']['4'] + assert_equal('3', root2['3']['4'].parent.name) # This is on the new tree + assert_nil(root1['2']['4']) # This is on the old tree end # Test the path_as_string method. def test_path_as_string - j = Tree::TreeNode.new("j") - f = Tree::TreeNode.new("f") - k = Tree::TreeNode.new("k") - a = Tree::TreeNode.new("a") - d = Tree::TreeNode.new("d") - h = Tree::TreeNode.new("h") - z = Tree::TreeNode.new("z") - p = Tree::TreeNode.new("p") - t = Tree::TreeNode.new("t") - e = Tree::TreeNode.new("e") + j = Tree::TreeNode.new('j') + f = Tree::TreeNode.new('f') + k = Tree::TreeNode.new('k') + a = Tree::TreeNode.new('a') + d = Tree::TreeNode.new('d') + h = Tree::TreeNode.new('h') + z = Tree::TreeNode.new('z') + p = Tree::TreeNode.new('p') + t = Tree::TreeNode.new('t') + e = Tree::TreeNode.new('e') # Create the following Tree # j <-- level 0 (Root) @@ -1690,7 +1685,7 @@ def test_path_as_string h << t j << k << z - assert_equal(t.path_as_string(), 'j=>f=>h=>t') # Check the default sep. + assert_equal(t.path_as_string, 'j=>f=>h=>t') # Check the default sep. assert_equal(t.path_as_string(' => '), 'j => f => h => t') assert_equal(z.path_as_string(' => '), 'j => k => z') @@ -1699,16 +1694,16 @@ def test_path_as_string # Test the path_as_array method. def test_path_as_array - j = Tree::TreeNode.new("j") - f = Tree::TreeNode.new("f") - k = Tree::TreeNode.new("k") - a = Tree::TreeNode.new("a") - d = Tree::TreeNode.new("d") - h = Tree::TreeNode.new("h") - z = Tree::TreeNode.new("z") - p = Tree::TreeNode.new("p") - t = Tree::TreeNode.new("t") - e = Tree::TreeNode.new("e") + j = Tree::TreeNode.new('j') + f = Tree::TreeNode.new('f') + k = Tree::TreeNode.new('k') + a = Tree::TreeNode.new('a') + d = Tree::TreeNode.new('d') + h = Tree::TreeNode.new('h') + z = Tree::TreeNode.new('z') + p = Tree::TreeNode.new('p') + t = Tree::TreeNode.new('t') + e = Tree::TreeNode.new('e') # Create the following Tree # j <-- level 0 (Root) @@ -1726,9 +1721,9 @@ def test_path_as_array h << t j << k << z - assert_equal(e.path_as_array, ['j', 'f', 'a', 'd', 'e']) - assert_equal(p.path_as_array, ['j', 'f' , 'h', 'p']) - assert_equal(k.path_as_array, ['j', 'k']) + assert_equal(e.path_as_array, %w(j f a d e)) + assert_equal(p.path_as_array, %w(j f h p)) + assert_equal(k.path_as_array, %w(j k)) end end end