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 11-20 of 29 total

test

// description of your code here

warum geht das nicht?

Refactoring of simple Model test for Rails

# =============================================================================
# Purpose: Refactored TestCase for simple Rails ActiveRecord::Base and 
#          ActiveForm classes.
# Author:  Manuel Holtgrewe <purestorm at ggnore dot net>
# License: Public Domain
#
# Feel free to flesh out the tests further and make it a more poweful library.
# Drop me a line if you find the module useful or if you created something more
# powerful on top of it.
# =============================================================================
#
# Include this module in your test classes. Then, you define some valid data,
# the model class to test and some "patches" to the valid data to make it invalid.
#
# Sure, this will only work for very simple models but you want to spend as few
# time on those as possible, right?
#
# Assuming you have the following model:
#
#   class MyModel < ActiveRecord::Base
#     validates_length_of :title, :in => 10..100
#     validates_numericality_of :number
#   end
#
# You can then write the following TestCase:
#
#  class MyModelTest < Test::Unit::TestCase
#    include SimpleMethodTests # The basic tests are defined in this module.
#
#    fixtures :my_models
#
#    def setup
#      @model_class = MyModel
#      @valid_data = { :title => 'Abracabra!', :number => 10 }
#      @invalid_patches =
#        [
#          [ :title, nil ], [ :title, 'a' * 9 ], [ :title, 'a' * 101 ],
#          [ :number, nil ], [ :number, 'a' ], [ :title, '123a' ],
#        ]
#    end
#
#    def test_a_nonbasic_test
#      flunk, "Wheee!"
#    end
#
#    # Overwrite a test from the mixin.
#    def test_valid_should_return_false_and_add_errors_with_invalid_data
#      assert true, "Removing this test!"
#    end
#  end
#
# You can both test ActiveRecord::Base and ActiveForm classes (CRUD is not tested
# on ActiveForm classes). If you test ActiveRecord::Base classes then you have to
# provide at least one fixture.
module SimpleModelTests
  def test_valid_should_return_true_with_valid_data
    # Do not use Model.new(attributes) since some might be marked as protected.
    model = @model_class.new
    @valid_data.each { |key, value| model.send("#{key}=".to_sym, value) }

    assert model.valid?
    assert_equal 0, model.errors.count
  end
  
  def test_valid_should_return_false_and_add_errors_with_invalid_data
    @invalid_patches.each do |key, value|
      invalid_data = @valid_data.dup
      invalid_data[key] = value
    
      # Do not use Model.new(attributes) since some might be marked as protected.
      model = @model_class.new
      invalid_data.each { |invalid_key, invalid_value| model.send("#{invalid_key}=".to_sym, invalid_value) }

      assert !model.valid?, "invalid_data[#{key.inspect}] == #{value.inspect}, errors: #{model.errors.full_messages.join('; ')}"
      
      # If the property we set was a foreign key named NAME_id then the error 
      # gets added to the property NAME of the object if the object is an
      # ActiveRecord::Base object.
      if key.to_s =~ /^(.*)_id$/ and model.respond_to?($1.to_sym) then
        assert_not_nil model.errors.on($1.to_sym), "invalid_data[#{$1.to_sym.inspect}] == #{value.inspect}"
      else
        assert_not_nil model.errors.on(key), "invalid_data[#{key.inspect}] == #{value.inspect}"
      end
    end
  end
  
  def test_create_should_work_correctly
    # We only want to test this if we test an ActiveRecord::Base class.
    return if not @model_class.new.respond_to?(:save)
    
    old_count = @model_class.count
    
    # Do not use Model.new(attributes) since some might be marked as protected.
    model = @model_class.new
    @valid_data.each { |key, value| model.send("#{key}=".to_sym, value) }
    
    assert model.save, "errors: #{model.errors.full_messages.join('; ')}"
    assert model.reload
    
    assert_equal old_count+1, @model_class.count
  end
  
  def test_update_should_work_correctly
    # We only want to test update if the model objects have a method "save".
    return if not @model_class.new.respond_to?(:update)
    
    # We assume that there is at least one valid record in the database with
    # different data than the @valid_data you specified above.
    #
    # We order by id to make the result predictable.
    model = @model_class.find(:first, :order => 'id ASC')
    
    @valid_data.each { |key, value| model.send("#{key}=".to_sym, value) }
  
    assert model.save, "errors: #{model.errors.full_messages.join('; ')}"
    assert model.reload
    
    @valid_data.each do |key, value|
      case value
      when Float then
        assert_in_delta value, model.send(key), 0.01
      else
        assert_equal value, model.send(key)
      end
    end
  end
  
  def test_destroy_should_work_correctly
    # We only want to test this if we test an ActiveRecord::Base class.
    return if not @model_class.new.respond_to?(:destroy)
    
    old_count = @model_class.count
    
    model = @model_class.find(:first)
    
    id = model.id
    
    model.destroy
    
    assert_raises(ActiveRecord::RecordNotFound) { @model_class.find(id) }
    
    assert_equal old_count-1, @model_class.count
  end
end

Petes test

// description of your code here

testing hello world!

REST curl helper

// A small bash script that wraps around curl to help more easily test RESTful sites.

#!/bin/bash
AUTH="user:password"
BASE="http://localhost:3000"
METHOD=$1
DEST="$BASE$2"
XML=$3

# make sure args were passed
if [ $# -eq 0 ]; then
        echo "usage: ./`basename $0` HTTP-METHOD DESTINATION_URI [XML]"
        echo "example: ./`basename $0` POST "/accounts" \"<account><name>ed</name><email>ed@ed.com</email></account>\""
        exit 1
fi

# execute CURL call
curl -H 'Accept: application/xml' -H 'Content-Type: application/xml' -w '\nHTTP STATUS: %{http_code}\nTIME: %{time_total}\n' \
-X $METHOD \
-d "$XML" \
-u "$AUTH" \
"$DEST"

exit 0

test post

// description of your code here

print "pippo"
printf("pippo: %d\n",a);

#post method in tests with a different controller

I wanted a #login method in test_helper that would allow me to easily login from any of my functional tests. However, the #post method won't allow you to set a different controller than the one in the @controller instance variable that's defined in your test's #setup. Well, by looking at how the #process method works, you can see that it just grabs the controller from @controller. Redefine that, and you're good to go:
old_controller = @controller
@controller = LoginController.new
post(
  :attempt_login,
  {:user => {:name => 'joe', :password => 'password'}}
)
@controller = old_controller

If you have several login methods, such as a #login_admin and #login_regular, you could make a wrapper to reduce duplication:
def wrap_with_controller( new_controller = LoginController )
  old_controller = @controller
  @controller = new_controller.new
  yield
  @controller = old_controller
end

def login_admin
  wrap_with_controller do
    post(
      :attempt_login,
      {:user => {:name => 'root', :password => 'password'}}
    )
  end
end

def login_regular
  wrap_with_controller do
    post(
      :attempt_login,
      {:user => {:name => 'joe', :password => 'password'}}
    )
  end
end

test

// description of your code here

//1:递归的就3行解决问题,�过呢比较挫的机�上溢出,整个�递归的
unsigned int Fibonacci(unsigned int a)
{
	unsigned int tmp[2]={0,1};
	bool flag = true;
	if(a == 0) return 0;
	if(a == 1) return 1;
	for(int i = 0; i < a-1; i++)
	{
		tmp[!flag] += tmp[flag];
		flag = !flag;
	}
	return tmp[flag];

}
void problem1(char* filename)
{
	ifstream infile(filename);
	assert(filename);
	int val;
	while(infile>>val)
         {cout<<Fibonacci(val)<<endl;}
	infile.close();
}

//2:就一体力活。。。
const static char keys[][13]=
{
	{'`', '1', '2', '3', '4', '5' ,'6', '7' ,'8' ,'9', '0', '-' ,'='},
	{'Q', 'W', 'E', 'R', 'T' ,'Y', 'U', 'I', 'O', 'P' ,'[', ']', '\\'},
	{'A' ,'S' ,'D' ,'F' ,'G' ,'H' ,'J', 'K' ,'L' ,';', '\''},
	{'Z',  'X' , 'C',  'V' , 'B' , 'N',  'M',  ',' , '.',  '/'}
};
static unsigned char charmap[256];
void buildmap()
{
	int i, j;
	for(i = 0; i < 256; i++)charmap[i] = i;
	for(j =0; j < 4; j++)
	for(i = 1; i < 13; i++)
	{
		if(keys[j][i])
		{
			charmap[keys[j][i]] = keys[j][i-1];
			if(keys[j][i] >= 'A' && keys[j][i] <= 'Z')
				charmap[keys[j][i]+32] = keys[j][i]+32;
		}
	}
	
}

void problem2(const char* filename)
{
	static bool isinitmap = false;
	int chr;
	FILE *fp = fopen(filename, "r");
	assert(filename);
	if(!isinitmap){ buildmap(); isinitmap = true;}
	while((chr = fgetc(fp)) != EOF)
	{
		printf("%c", (char)charmap[chr]);
		
		
	}
	fclose(fp);
	
}
#if 0
3:如果对STL的string有那么一点点了解的�会比较简�,如果想裸写KMP,
还是比较困难,�过暴力的O(m*n)的倒是简�,估计也能accept :-)
#endif 
typedef basic_string<char>::size_type str_pos;
int string_shift(string& T, string P)
{
	str_pos start = -1;
	int shift_cnt = 0;
	while((start = T.find(P, start+1)) != -1)shift_cnt++;
	return shift_cnt;
}
void strshift(char* filename)
{
	ifstream infile(filename);
	assert(infile);
	string T, P;
	while(infile>>T>>P)cout << string_shift(T, P)<<endl;
	infile.close();
}

//4:一个简�的办法就是递归啦,�过注�2的表示是2 �是2(2(0))就好了。
#define BITMASK (0x1<<31)
void exponentform(unsigned int a)
{
	if(a == 0 || a == 2)
	{
		cout << a;
		return;
	}
	for(int i = 31; i > -1; i--)
	{
		if(a & BITMASK)
		{
			if(i == 1)
			{
				cout << "2";
			}
			else 
			{
				cout<<"2(";
				exponentform(i);
				cout << ")";
			}
			if(a<<1)cout << "+";
			//
		}
		a <<= 1;
	}
}

void problem4(char* filename)
{
	ifstream infile(filename);
	int val;
	while(infile>>val)
	{
		exponentform(val);
		puts("");
	}
	infile.close();
}

test if sites are online

// test if sites are online by title validation
// if the title can change, test can validate occurance of a phrase instead

require 'rwebunit'  # ruby web test based on watir (uses ie=internet-explorer-object)

# test if sites are online by title validation
# usage: to run this test without visible ie use the -b option
# C:\ruby\workspace\ruject1>ruby rwu_site_checker.rb -b

class RwuSiteChecker < RWebUnit::WebTestCase

  # hash with url and title
  @@sites = {
    "http://www.domain_number_one.de" => "title number one",
    "http://www.seccond_domain.org" => "seccond title",
    "http://www.yet_another_domain.com" => "yet another title"
  }
  
  # test for titles
  def test_titles()
    log = "testing title \n"
    @@sites.each { |url, title|
      getTestContext().base_url=url
      beginAt("/")
      assertTitleEquals(title)
      # to check for phrase: assertTextPresent(phrase) 
   
      log += url + " ok \n"
    }
    puts log
  end
  
end

a test post

// description of your code here
google
2

ok, link has size limit.

Testing from Class

Testing from class at Tue Jul 18 21:58:13 EDT 2006
« Newer Snippets
Older Snippets »
Showing 11-20 of 29 total