The best kittens, technology, and video games blog in the world.

Monday, July 03, 2006

Unit testing

Good karma for Ruby and for Extreme Programming today. I've just tried to port libgmp-ruby from handmade testing system to Test::Unit. It is totally sweet:


#!/usr/bin/ruby

require 'test/unit'
require 'gmp'

class TC_Z < Test::Unit::TestCase
   def test_init_null
       assert_equal(GMP::Z.new(), 0, "GMP::Z.new() should initialize to 0")
   end

   def test_init_fixnum
       assert_equal(GMP::Z.new(1), 1, "GMP::Z.new(x : Fixnum) should initialize to x")
   end

   def test_init_z
       b = GMP::Z.new(1)
       assert_equal(GMP::Z.new(b), b, "GMP::Z.new(x : GMP::Z) should initialize to x")
   end

   def test_init_string
       assert_equal(GMP::Z.new("1"), 1, "GMP::Z.new(x : String) should initialize to x")
   end

   def test_init_bignum
       assert_equal(GMP::Z.new(2**32), 2**32, "GMP::Z.new(x : Bignum) should initialize to x")
   end
end
Executing this script runs all the tests:

$ ./unit_tests_1.rb
Loaded suite ./unit_tests_1
Started
.....
Finished in 0.006574 seconds.

5 tests, 5 assertions, 0 failures, 0 errors
Do you see any executable code, any list of tests to run ? Nah, it works by smoke and mirrors. We're going to leave XML BDSM to Java programmers, they seem to like it. ;-) It even found an actual bug in libgmp-ruby (something was pointing the wrong way around) in the first 5 minutes of testing. That's kinda cool. You can use multiple assertions per test, fixtures and so on. It still works by magic.

class TC_Q_Basic < Test::Unit::TestCase
   def setup
       @a=GMP::Q.new(100,11)
       @b=GMP::Q.new(200,17)
       @c=GMP::Z.new(40)
       @d=2**32
   end

   def test_add
       assert_equal(@a + @b, GMP::Q(3900, 187),       "GMP::Q should add GMP::Q correctly")
       assert_equal(@a + @c, GMP::Q(540,  11),        "GMP::Q should add GMP::Z correctly")
       assert_equal(@c + @a, GMP::Q(540,  11),        "GMP::Z should add GMP::Q correctly")
       assert_equal(@a +  2, GMP::Q(122,  11),        "GMP::Z should add Fixnum correctly")
       assert_equal(@a + @d, GMP::Q(47244640356, 11), "GMP::Z should add Bignum correctly")
       assert_equal( 2 + @a, GMP::Q(122,  11),        "Fixnum should add GMP::Q correctly")
       assert_equal(@d + @a, GMP::Q(47244640356, 11), "Bignum should add GMP::Q correctly")
   end
end

3 comments:

DiZzy said...

What is the current status of libgmp-ruby? It seems the only available version is 1.0 cached at RAA, all other links are pointing to 0xDEADBEEF.
This library rocks - i've used it to bypass ruby's "warning: in a**b, b may be too big".

Please, publish the recent sources. And a todo list for them too - improving the library seems to be a good Ruby-C task for me. =)

taw said...

Alexey: I'll try to make some publishable version in the next few days.

taw said...

Alexey: I released a tarball. Tell me if you need some help with getting it working.