Delving the depths of computing,
hoping not to get eaten by a wumpus

By Timm Murray

Don't use is() in Test::More

2015-06-19


#!perl
use v5.14;
use warnings;
use Test::More tests => 2;

my $val = "2.123450";

is( $val, 2.123450 );
cmp_ok( $val, '==', 2.123450 );

This results in:

1..2
not ok 1
#   Failed test at tmp/bad_is.pl line 9.
#          got: '2.123450'
#     expected: '2.12345'
ok 2
# Looks like you failed 1 test of 2.

The issue is fairly obvious when it’s laid out like this: is() does a string comparison, which means that trailing zero matters. One day, though, I promise you, you’ll hit a problem like this and will spend hours debugging it, only to smack your forehead when you finally see it. You can prevent that by explicitly giving a comparison operator to cmp_ok() instead.

This is somewhat similar to the issues seen in the ‘==’ operator in JavaScript and PHP, where the language makes a guess about how to coerce the types and gets it wrong (or at least, produces unexpected behavior). Those languages invented ‘===’ to solve that, which is madness.



Copyright © 2024 Timm Murray
CC BY-NC

Opinions expressed are solely my own and do not express the views or opinions of my employer.