Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 29 total  RSS 

test

// test

   1  
   2  #load all factories...
   3  load_path = File.dirname(__FILE__) + "/factories/"
   4  Dir.new(load_path).each do |f|
   5    full_path = load_path + f
   6    unless File.directory?(full_path)
   7      load full_path
   8    end
   9  end

How to eat an elephant in Java

How do you eat an elephant? Well, 'bite by bite', they told me. In Java, this may look like this:

   1  
   2    Elephant elephant = ...; // get the elephant from somewhere
   3  
   4    while (!elephant.isEatenCompletely()) {
   5      elephant.haveOneBite();
   6    }
   7  


Why am I writing this? Well, simply to test my dzone account ;)

Point Inside a Polygon //JavaScript Function


Checks whether a point is inside a polygon.
Adapted from: [http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html]

[UPDATED CODE AND HELP CAN BE FOUND HERE: Point Inside a Polygon]



   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com/classes/is-point-in-poly [v1.0]
   4  
   5  function isPointInPoly(poly, pt){
   6  	for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
   7  		((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
   8  		&& (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
   9  		&& (c = !c);
  10  	return c;
  11  }


Example

   1  
   2  <script type="text/javascript">
   3  //<![CDATA[
   4  
   5  points = [
   6  	{x: 0, y: 0},
   7  	{x: 0, y: 50},
   8  	{x: 50, y: 10},
   9  	{x: -50, y: -10},
  10  	{x: 0, y: -50},
  11  	{x: 0, y: 0}
  12  ];
  13  
  14  alert(isPointInPoly(points, {x: 10, y: 10}) ? "In" : "Out");
  15  
  16  //]]>
  17  </script>

Make Time "Stand Still" in Ruby

When writing tests, it's sometimes difficult to test results of methods that use current time. Two calls to Time.now can give different results and cause test failures. Here is some code that lets you execute a block during which Time.now will return a consistent value:

   1  
   2  class Time
   3  
   4    # this code adds a Time.freeze method to make time "stand still"
   5    # during execution of a block. This can be helpful during testing of
   6    # methods that depend on Time.new or Time.now
   7    #
   8    # Example:
   9    #
  10    #   Time.freeze do
  11    #      puts Time.new.to_f
  12    #      # ... do stuff; real time passes
  13    #      puts Time.new.to_f     # outputs same time as above
  14    #   end
  15    #   # ... time returns to normal
  16    #
  17    # An optional Time object may be passed to freeze to a specific time:
  18    #
  19    #   Time.freeze(Time.at(2007, 11, 15)) do
  20    #      # ...
  21    #   end
  22    #
  23    # While inside the block, Time.frozen? will return true
  24  
  25    class << self
  26  
  27      def now
  28        @time || orig_new
  29      end
  30  
  31      alias_method :orig_freeze, :freeze
  32      alias_method :orig_new, :new
  33      alias_method :new, :now
  34  
  35      # makes time "stand still" during execution of a block. if no time is
  36      # supplied, the current time is used. While in the block, Time.new and
  37      # Time.now will always return the "frozen" value.
  38      def freeze(time = nil)
  39        raise "A block is required" unless block_given?
  40        begin
  41          prev = @time
  42          @time = time || now
  43          yield
  44        ensure
  45          @time = prev
  46        end
  47      end
  48  
  49      def frozen?
  50        !@time.nil?
  51      end
  52  
  53    end
  54  end

Save db data to fixture files

rake db:fixtures:dump_all
он сохранит все данные из ваших таблиц development базы в ямлы для тестов rake

db:fixtures:dump_references
["areas","countries"]
сохранит только те таблицы которы епрописаны у него в конфиге, в данном случае это

   1  
   2  namespace :db do
   3    namespace :fixtures do
   4  
   5      desc 'Create YAML test fixtures from data in an existing database.
   6  Defaults to development database. Set RAILS_ENV to override.'
   7      task :dump_all => :environment do
   8        sql = "SELECT * FROM %s"
   9        skip_tables = ["schema_info"]
  10        ActiveRecord::Base.establish_connection(:development)
  11        (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
  12          i = "000"
  13          File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
  14            data = ActiveRecord::Base.connection.select_all(sql % table_name)
  15            file.write data.inject({}) { |hash, record|
  16              hash["#{table_name}_#{i.succ!}"] = record
  17              hash
  18            }.to_yaml
  19          end
  20        end
  21      end
  22    end
  23    
  24    namespace :fixtures do
  25      desc 'Create YAML test fixtures for references. Defaults to development database. 
  26      Set RAILS_ENV to override.'
  27      task :dump_references => :environment do
  28        sql = "SELECT * FROM %s"
  29        dump_tables = ["areas","countries"]
  30        ActiveRecord::Base.establish_connection(:development)
  31        dump_tables.each do |table_name|
  32          i = "000"
  33          file_name = "#{RAILS_ROOT}/test/fixtures/#{table_name}.yml"
  34          p "Fixture save for table #{table_name} to #{file_name}"
  35          File.open(file_name, 'w') do |file|
  36            data = ActiveRecord::Base.connection.select_all(sql % table_name)
  37            file.write data.inject({}) { |hash, record|
  38              hash["#{table_name}_#{i.succ!}"] = record
  39              hash
  40            }.to_yaml
  41          end
  42        end
  43      end
  44    end
  45  end 
  46  

A simple test case using Ruby and XML - Part III

This Ruby CGI script tests a class, by reading the testdata from an XML file, then outputs the result to the web browser. Refer to parts 1 http://urltea.com/1p7h [dzone.com], and II http://urltea.com/1p7m [dzone.com]

   1  
   2  #file: test-feed.cgi
   3  
   4  require 'test_feed'
   5  
   6  puts "Content-Type: text/xml"
   7  puts
   8  
   9  puts "<test_report>"
  10  tf = Test_feed.new()
  11  puts tf.plan
  12  puts "<actual>"
  13  tf.print('create_file', tf.tested)
  14  puts "</actual>"
  15  puts "</test_report>"

A simple test case using Ruby and XML - Part II

This code tests for the success of a single Class. It reads in the test variables from an xml file and then performs a simple test. Refer to Part I (http://urltea.com/1p7h [dzone.com]) of the ruby code (testdata.rb), and Part III (http://urltea.com/1p7p [dzone.com])

   1  
   2  #file: test_feed.rb
   3  
   4  require 'testdata.rb'
   5  require 'feed.rb'
   6  
   7  include REXML
   8  
   9  class Test_feed < Testdata
  10  
  11    def initialize()
  12  
  13      url = 'http://jamesrobertson.eu/test/feed/'
  14      testfile = "testfile.xml"
  15      load(url + testfile)
  16  
  17      @in_filepath = get_input('filepath')
  18      @in_project = get_input('project')
  19      @in_date = get_input('date')
  20      @out_filepath = get_output('filepath')
  21      @out_file = get_output('file')
  22    end
  23  
  24    def tested
  25      feed = Feed.new
  26      feed.create_file(@in_filepath, @in_project)
  27      File.exist?(@out_filepath + @out_file)
  28    end
  29  
  30  end
  31  
  32  #test 
  33  #test_feed = Test_feed.new()
  34  #puts test_feed.tested

A simple test case using Ruby and XML - Part I

Inspired by Gregg Pollack's, Ruby on Rails testing video http://tinyurl.com/ystb4o, this code reads an XML file containing test related variables, to use in an actual test case. Refer to parts II (http://urltea.com/1p7m [dzone.com]), and III (http://urltea.com/1p7p [dzone.com])

   1  
   2  #file: testdata.rb
   3  
   4  require 'net/http'
   5  require 'rexml/document'
   6  
   7  include REXML
   8  
   9  class Testdata
  10  
  11    def initialize
  12    end
  13  
  14    def load(url)
  15      xml_data = Net::HTTP.get_response(URI.parse(url)).body
  16      @doc = Document.new(xml_data)
  17      true
  18    end
  19  
  20    def get_input(name)
  21      @doc.root.elements['test/inputs/input/' + name].text
  22    end
  23  
  24    def get_output(name)
  25      @doc.root.elements['test/outputs/output/' + name].text
  26    end
  27  
  28    def tested?()
  29  
  30    end
  31  
  32    def print(method, result)
  33      puts "<result method='#{method}'>#{result}</result>"
  34    end
  35  
  36    def plan
  37      @doc
  38    end
  39  
  40  end
  41  
  42  #test 
  43  #url = 'http://m.jamesrobertson.eu/test/testdata/'
  44  #testfile = "testfile.xml"
  45  
  46  #td = Testdata.new
  47  #td.load(url + testfile)
  48  #print('get_input', #td.get_input('input1').scan('instring').length > 0)
  49  #print('get_output', td.get_output('output1').scan('outstring').length > 0)
  50  
  51  #puts test_feed.tested?


dit is een test

// description of your code here

   1  
   2  // insert code here..

truncate Rails development/test logs

In rails applications development.log and test.log like to grow forever, which takes up space and makes them slow to grep. If I just delete them running processes with logs open might get confused. So I can use truncate instead:

   1  
   2  truncate ~/www/*/log/*.log


Even easier, ask cron to do it for me every night:
   1  
   2  4 22 * * * * truncate -s 0k  ~/www/*/log/*.log
« Newer Snippets
Older Snippets »
Showing 1-10 of 29 total  RSS