Categories
Posts in this category
- Current State of Exceptions in Rakudo and Perl 6
- Meet DBIish, a Perl 6 Database Interface
- doc.perl6.org and p6doc
- Exceptions Grant Report for May 2012
- Exceptions Grant Report -- Final update
- Perl 6 Hackathon in Oslo: Be Prepared!
- Localization for Exception Messages
- News in the Rakudo 2012.05 release
- News in the Rakudo 2012.06 release
- Perl 6 Hackathon in Oslo: Report From The First Day
- Perl 6 Hackathon in Oslo: Report From The Second Day
- Quo Vadis Perl?
- Rakudo Hack: Dynamic Export Lists
- SQLite support for DBIish
- Stop The Rewrites!
- Upcoming Perl 6 Hackathon in Oslo, Norway
- A small regex optimization for NQP and Rakudo
- Pattern Matching and Unpacking
- Rakudo's Abstract Syntax Tree
- The REPL trick
- First day at YAPC::Europe 2013 in Kiev
- YAPC Europe 2013 Day 2
- YAPC Europe 2013 Day 3
- A new Perl 6 community server - call for funding
- New Perl 6 community server now live, accepting signups
- A new Perl 6 community server - update
- All Perl 6 modules in a box
- doc.perl6.org: some stats, future directions
- Profiling Perl 6 code on IRC
- Why is it hard to write a compiler for Perl 6?
- Writing docs helps you take the user's perspective
- Perl 6 Advent Calendar 2016 -- Call for Authors
- Perl 6 By Example: Running Rakudo
- Perl 6 By Example: Formatting a Sudoku Puzzle
- Perl 6 By Example: Testing the Say Function
- Perl 6 By Example: Testing the Timestamp Converter
- Perl 6 By Example: Datetime Conversion for the Command Line
- What is Perl 6?
- Perl 6 By Example, Another Perl 6 Book
- Perl 6 By Example: Silent Cron, a Cron Wrapper
- Perl 6 By Example: Testing Silent Cron
- Perl 6 By Example: Stateful Silent Cron
- Perl 6 By Example: Perl 6 Review
- Perl 6 By Example: Parsing INI files
- Perl 6 By Example: Improved INI Parsing with Grammars
- Perl 6 By Example: Generating Good Parse Errors from a Parser
- Perl 6 By Example: A File and Directory Usage Graph
- Perl 6 By Example: Functional Refactorings for Directory Visualization Code
- Perl 6 By Example: A Unicode Search Tool
- What's a Variable, Exactly?
- Perl 6 By Example: Plotting using Matplotlib and Inline::Python
- Perl 6 By Example: Stacked Plots with Matplotlib
- Perl 6 By Example: Idiomatic Use of Inline::Python
- Perl 6 By Example: Now "Perl 6 Fundamentals"
- Perl 6 Books Landscape in June 2017
- Living on the (b)leading edge
- The Loss of Name and Orientation
- Perl 6 Fundamentals Now Available for Purchase
- My Ten Years of Perl 6
- Perl 6 Coding Contest 2019: Seeking Task Makers
- A shiny perl6.org site
- Creating an entry point for newcomers
- An offer for software developers: free IRC logging
- Sprixel, a 6 compiler powered by JavaScript
- Announcing try.rakudo.org, an interactive Perl 6 shell in your browser
- Another perl6.org iteration
- Blackjack and Perl 6
- Why I commit Crud to the Perl 6 Test Suite
- This Week's Contribution to Perl 6 Week 5: Implement Str.trans
- This Week's Contribution to Perl 6
- This Week's Contribution to Perl 6 Week 8: Implement $*ARGFILES for Rakudo
- This Week's Contribution to Perl 6 Week 6: Improve Book markup
- This Week's Contribution to Perl 6 Week 2: Fix up a test
- This Week's Contribution to Perl 6 Week 9: Implement Hash.pick for Rakudo
- This Week's Contribution to Perl 6 Week 11: Improve an error message for Hyper Operators
- This Week's Contribution to Perl 6 - Lottery Intermission
- This Week's Contribution to Perl 6 Week 3: Write supporting code for the MAIN sub
- This Week's Contribution to Perl 6 Week 1: A website for proto
- This Week's Contribution to Perl 6 Week 4: Implement :samecase for .subst
- This Week's Contribution to Perl 6 Week 10: Implement samespace for Rakudo
- This Week's Contribution to Perl 6 Week 7: Implement try.rakudo.org
- What is the "Cool" class in Perl 6?
- Report from the Perl 6 Hackathon in Copenhagen
- Custom operators in Rakudo
- A Perl 6 Date Module
- Defined Behaviour with Undefined Values
- Dissecting the "Starry obfu"
- The case for distributed version control systems
- Perl 6: Failing Softly with Unthrown Exceptions
- Perl 6 Compiler Feature Matrix
- The first Perl 6 module on CPAN
- A Foray into Perl 5 land
- Gabor: Keep going
- First Grant Report: Structured Error Messages
- Second Grant Report: Structured Error Messages
- Third Grant Report: Structured Error Messages
- Fourth Grant Report: Structured Error Messages
- Google Summer of Code Mentor Recap
- How core is core?
- How fast is Rakudo's "nom" branch?
- Building a Huffman Tree With Rakudo
- Immutable Sigils and Context
- Is Perl 6 really Perl?
- Mini-Challenge: Write Your Prisoner's Dilemma Strategy
- List.classify
- Longest Palindrome by Regex
- Perl 6: Lost in Wonderland
- Lots of momentum in the Perl 6 community
- Monetize Perl 6?
- Musings on Rakudo's spectest chart
- My first executable from Perl 6
- My first YAPC - YAPC::EU 2010 in Pisa
- Trying to implement new operators - failed
- Programming Languages Are Not Zero Sum
- Perl 6 notes from February 2011
- Notes from the YAPC::EU 2010 Rakudo hackathon
- Let's build an object
- Perl 6 is optimized for fun
- How to get a parse tree for a Perl 6 Program
- Pascal's Triangle in Perl 6
- Perl 6 in 2009
- Perl 6 in 2010
- Perl 6 in 2011 - A Retrospection
- Perl 6 ticket life cycle
- The Perl Survey and Perl 6
- The Perl 6 Advent Calendar
- Perl 6 Questions on Perlmonks
- Physical modeling with Math::Model and Perl 6
- How to Plot a Segment of a Circle with SVG
- Results from the Prisoner's Dilemma Challenge
- Protected Attributes Make No Sense
- Publicity for Perl 6
- PVC - Perl 6 Vocabulary Coach
- Fixing Rakudo Memory Leaks
- Rakudo architectural overview
- Rakudo Rocks
- Rakudo "star" announced
- My personal "I want a PONIE" wish list for Rakudo Star
- Rakudo's rough edges
- Rats and other pets
- The Real World Strikes Back - or why you shouldn't forbid stuff just because you think it's wrong
- Releasing Rakudo made easy
- Set Phasers to Stun!
- Starry Perl 6 obfu
- Recent Perl 6 Developments August 2008
- The State of Regex Modifiers in Rakudo
- Strings and Buffers
- Subroutines vs. Methods - Differences and Commonalities
- A SVG plotting adventure
- A Syntax Highlighter for Perl 6
- Test Suite Reorganization: How to move tests
- The Happiness of Design Convergence
- Thoughts on masak's Perl 6 Coding Contest
- The Three-Fold Function of the Smart Match Operator
- Perl 6 Tidings from September and October 2008
- Perl 6 Tidings for November 2008
- Perl 6 Tidings from December 2008
- Perl 6 Tidings from January 2009
- Perl 6 Tidings from February 2009
- Perl 6 Tidings from March 2009
- Perl 6 Tidings from April 2009
- Perl 6 Tidings from May 2009
- Perl 6 Tidings from May 2009 (second iteration)
- Perl 6 Tidings from June 2009
- Perl 6 Tidings from August 2009
- Perl 6 Tidings from October 2009
- Timeline for a syntax change in Perl 6
- Visualizing match trees
- Want to write shiny SVG graphics with Perl 6? Port Scruffy!
- We write a Perl 6 book for you
- When we reach 100% we did something wrong
- Where Rakudo Lives Now
- Why Rakudo needs NQP
- Why was the Perl 6 Advent Calendar such a Success?
- What you can write in Perl 6 today
- Why you don't need the Y combinator in Perl 6
- You are good enough!
Sun, 18 Dec 2016
Perl 6 By Example: Testing the Timestamp Converter
Permanent link
This blog post is part of my ongoing project to write a book about Perl 6.
If you're interested, either in this book project or any other Perl 6 book news, please sign up for the mailing list at the bottom of the article, or here. It will be low volume (less than an email per month, on average).
In the previous installment, we've seen some code go through several iterations of refactoring. Refactoring without automated tests tends to make me uneasy, so I actually had a small shell script that called the script under development with several different argument combinations and compared it to an expected result.
Let's now look at a way to write test code in Perl 6 itself.
As a reminder, this is what the code looked like when we left it:
#!/usr/bin/env perl6
#| Convert timestamp to ISO date
multi sub MAIN(Int \timestamp) {
sub formatter($_) {
sprintf '%04d-%02d-%02d %02d:%02d:%02d',
.year, .month, .day,
.hour, .minute, .second,
}
given DateTime.new(+timestamp, :&formatter) {
when .Date.DateTime == $_ { say .Date }
default { .say }
}
}
#| Convert ISO date to timestamp
multi sub MAIN(Str $date where { try Date.new($_) }, Str $time?) {
my $d = Date.new($date);
if $time {
my ( $hour, $minute, $second ) = $time.split(':');
say DateTime.new(date => $d, :$hour, :$minute, :$second).posix;
}
else {
say $d.DateTime.posix;
}
}
In the Perl community it's common to move logic into modules to make it easier to test with external test scripts. In Perl 6, that's still common, but for small tools such as this, I prefer to stick with a single file containing code and tests, and to run the tests via a separate test command.
To make testing easier, let's first separate I/O from the application logic:
#!/usr/bin/env perl6
sub from-timestamp(Int \timestamp) {
sub formatter($_) {
sprintf '%04d-%02d-%02d %02d:%02d:%02d',
.year, .month, .day,
.hour, .minute, .second,
}
given DateTime.new(+timestamp, :&formatter) {
when .Date.DateTime == $_ { return .Date }
default { return $_ }
}
}
sub from-date-string(Str $date, Str $time?) {
my $d = Date.new($date);
if $time {
my ( $hour, $minute, $second ) = $time.split(':');
return DateTime.new(date => $d, :$hour, :$minute, :$second);
}
else {
return $d.DateTime;
}
}
#| Convert timestamp to ISO date
multi sub MAIN(Int \timestamp) {
say from-timestamp(+timestamp);
}
#| Convert ISO date to timestamp
multi sub MAIN(Str $date where { try Date.new($_) }, Str $time?) {
say from-date-string($date, $time).posix;
}
With this small refactoring out of the way, let's add some tests:
#| Run internal tests
multi sub MAIN('test') {
use Test;
plan 4;
is-deeply from-timestamp(1450915200), Date.new('2015-12-24'),
'Timestamp to Date';;
my $dt = from-timestamp(1450915201);
is $dt, "2015-12-24 00:00:01",
'Timestamp to DateTime with string formatting';
is from-date-string('2015-12-24').posix, 1450915200,
'from-date-string, one argument';
is from-date-string('2015-12-24', '00:00:01').posix, 1450915201,
'from-date-string, two arguments';
}
And you can run it:
./autotime test
1..4
ok 1 - Timestamp to Date
ok 2 - Timestamp to DateTime with string formatting
ok 3 - from-date-string, one argument
ok 4 - from-date-string, two arguments
The output format is that of the Test Anything Protocol
(TAP), which is the de facto standard in the
Perl community, but is now also used in other communities. For larger output
strings it is a good idea to run the tests through a test harness. For our
four lines of test output, this isn't yet necessary, but if you want to do
that anyway, you can use the prove
program that's shipped with Perl 5:
$ prove -e "" "./autotime test"
./autotime-tested.p6 test .. ok
All tests successful.
Files=1, Tests=4, 0 wallclock secs ( 0.02 usr 0.01 sys + 0.23 cusr 0.02 csys = 0.28 CPU)
Result: PASS
In a terminal, this even colors the "All tests successful" output in green, to make it easier to spot. Test failures are marked up in red.
How does the testing work? The first line of code uses a new feature we haven't seen yet:
multi sub MAIN('test') {
What's that, a literal instead of a parameter in the subroutine signature? That's right. And it's a shortcut for
multi sub MAIN(Str $anon where {$anon eq 'test'}) {
except that it does not declare the variable $anon
. So it's a multi
candidate that you can only call by supplying the string 'test'
as the
sole argument.
The next line, use Test;
, loads the test
module that's shipped with Rakudo
Perl 6. It also imports into the current lexical scope all the symbols that
Test
exports by default. This includes the functions plan
, is
and
is-deeply
that are used later on.
plan 4
declares that we want to run four tests. This is useful for
detecting unplanned, early exits from the test code, or errors in looping
logic in the test code that leads to running fewer tests than planned.
If you can't be bothered to count your tests in advance, you can leave out
the plan
call, and instead call done-testing
after your tests are done.
Both is-deeply
and is
expect the value to be tested as the first
argument, the expected value as the second argument, and an optional test
label string as the third argument. The difference is that is()
compares
the first two arguments as strings, whereas is-deeply
uses a deep equality
comparison logic using the eqv
operator. Such tests only pass if the
two arguments are of the same type, and recursively are (or contain) the same
values.
More testing functions are available, like ok()
, which succeeds for a
true argument, and nok()
, which expects a false argument. You can also
nest tests with subtest
:
#| Run internal tests
multi sub MAIN('test') {
use Test;
plan 2;
subtest 'timestamp', {
plan 2;
is-deeply from-timestamp(1450915200), Date.new('2015-12-24'),
'Date';;
my $dt = from-timestamp(1450915201);
is $dt, "2015-12-24 00:00:01",
'DateTime with string formatting';
};
subtest 'from-date-string', {
plan 2;
is from-date-string('2015-12-24').posix, 1450915200,
'one argument';
is from-date-string('2015-12-24', '00:00:01').posix, 1450915201,
'two arguments';
};
}
Each call to subtest
counts as a single test to the outer test run, so
plan 4;
has become plan 2;
. The subtest call has a test label itself,
and then inside a subtest, you have a plan again, and calls to test
functions as below. This is very useful when writing custom test functions
that execute a variable number of individual tests.
The output from the nested tests looks like this:
1..2
1..2
ok 1 - Date
ok 2 - DateTime with string formatting
ok 1 - timestamp
1..2
ok 1 - one argument
ok 2 - two arguments
ok 2 - from-date-string
The test harness now reports just the two top-level tests as the number of run (and passed) tests.
And yes, you can nest subtests within subtests, should you really feel the urge to do so.