Will Parsons
2/5/2009 1:36:00 AM
Rob Biedenharn wrote:
> On Feb 4, 2009, at 5:59 PM, Will Parsons wrote:
>
>> I'm having trouble trying to figure out how to customize an assertion
>> message when running unit tests. In particular, I want to check the
>> permissions on a file, so I have something like:
>>
>> assert_equal(0755, File.stat(test_file).mode & 0777)
>>
>> If it fails, I get a message like:
>>
>> <493> expected but was
>> <420>.
>>
>> and of course I would like the expected and actual permissions to be
>> displayed in octal rather than decimal. How can I do that?
>
> Perhaps something like:
>
> $ ruby -r'test/unit'
> class SomeTest < Test::Unit::TestCase
> def setup
> @test_file = 'some_file'
> File.open(@test_file, 'w') {|f| f.write "Hello!"}
> end
> def test_bad_file_mode
> File.chmod(0644, @test_file)
>
> assert_equal '0755', '%#o'%[File.stat(@test_file).mode & 0777],
> "Mode of #{@test_file}"
> end
>
> def test_good_file_mode
> File.chmod(0755, @test_file)
>
> assert_equal '0755', '%#o'%[File.stat(@test_file).mode & 0777],
> "Mode of #{@test_file}"
> end
> end
> __END__
> Loaded suite -
> Started
> F.
> Finished in 0.025823 seconds.
>
> 1) Failure:
> test_bad_file_mode(SomeTest) [-:9]:
> Mode of some_file.
><"0755"> expected but was
><"0644">.
>
> 2 tests, 2 assertions, 1 failures, 0 errors
This is certainly an improvement on my version, but it is not completely
satisfying - the reason being that by explicitly converting the permissions
to a string they get displayed as strings, i.e., I would like to see:
<755> expected
rather than:
<"0755"> expected
> Note that I'm doing the conversion to octal myself with the '%#o' and
> String#%
>
> It would be better to pull this into a helper method:
>
> $ ruby -r'test/unit'
> class SomeTest < Test::Unit::TestCase
> def assert_mode(expected_mode, actual_mode, message=nil)
> assert_equal '%#o'%expected_mode, '%#o'%actual_mode, message
> end
>
> def setup
> @test_file = 'some_file'
> File.open(@test_file, 'w') {|f| f.write "Hello!"}
> end
> def test_bad_file_mode
> File.chmod(0644, @test_file)
>
> assert_mode 0755, File.stat(@test_file).mode & 0777, "Mode of
> #{@test_file}"
> end
>
> def test_good_file_mode
> File.chmod(0755, @test_file)
>
> assert_mode 0755, File.stat(@test_file).mode & 0777, "Mode of
> #{@test_file}"
> end
> end
> __END__
> Loaded suite -
> Started
> F.
> Finished in 0.0107 seconds.
>
> 1) Failure:
> test_bad_file_mode(SomeTest)
> [-:3:in `assert_mode'
> -:13:in `test_bad_file_mode']:
> Mode of some_file.
><"0755"> expected but was
><"0644">.
>
> 2 tests, 2 assertions, 1 failures, 0 errors
I'm not sure I understand this - what's the advantage of defining the
assert_mode method over using the already defined methods?
> Do you really want
> assert File.stat(@test_file).executable?
> instead of a specific mode?
Yes, because I want also to check for being read-only in addition to being
executable in the file permissions.
--
Will