Skip to content

Instantly share code, notes, and snippets.

@melo
Created June 18, 2010 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save melo/443949 to your computer and use it in GitHub Desktop.
Save melo/443949 to your computer and use it in GitHub Desktop.
#!perl
use strict;
use warnings;
use Test::More;
use MyClass;
use DateTime;
my ($c);
## From Int
$c = MyClass->new(bday => 1276881490);
is(
DateTime->compare(
$c->bday, DateTime->new(year => 2010, month => 6, day => 18)
),
0,
'Int coercion ok: '.$c->bday
);
## From Str
$c = MyClass->new(bday => '2010-06-18 18:18:10');
is(
DateTime->compare(
$c->bday, DateTime->new(year => 2010, month => 6, day => 18)
),
0,
'Str coercion ok: '.$c->bday
);
## From HashRef
$c = MyClass->new(bday => {year => 2010, month => 6, day => 18, hour => 1});
is(
DateTime->compare(
$c->bday, DateTime->new(year => 2010, month => 6, day => 18)
),
0,
'HashRef coercion ok: '.$c->bday
);
## From DateTime
$c =
MyClass->new(
bday => DateTime->new({year => 2010, month => 6, day => 18, hour => 1}));
is(
DateTime->compare(
$c->bday, DateTime->new(year => 2010, month => 6, day => 18)
),
0,
'pDateTime coercion ok: '.$c->bday
);
done_testing();
package MyClass;
use Moose;
use MyTypes qw( MyDate );
use namespace::clean -except => 'meta';
has bday => (isa => MyDate, is => 'ro', coerce => 1);
__PACKAGE__->meta->make_immutable;
1;
package MyTypes;
use strict;
use warnings;
use feature 'say';
use MooseX::Types -declare => [qw( MyDate )];
use MooseX::Types::Moose qw( Str Int HashRef Object );
use DateTime;
use DateTime::Format::MySQL;
class_type 'DateTime';
subtype MyDate, as Object;
coerce MyDate,
from Int, via {
say "# Int: $_";
DateTime->from_epoch(epoch => $_)->truncate(to => 'day');
},
from Str, via {
say "# Str: $_";
DateTime::Format::MySQL->parse_datetime($_)->truncate(to => 'day');
},
from HashRef, via {
say "# HashRef: $_";
DateTime->new(%$_)->truncate(to => 'day');
},
from 'DateTime', via {
say "# DateTime: $_";
$_->clone->truncate(to => 'day');
},
;
1;
$ prove -lv
t/coercions.t ..
# Int: 1276881490
ok 1 - Int coercion ok: 2010-06-18T00:00:00
# Str: 2010-06-18 18:18:10
ok 2 - Str coercion ok: 2010-06-18T00:00:00
# HashRef: HASH(0xab4990)
ok 3 - HashRef coercion ok: 2010-06-18T00:00:00
not ok 4 - pDateTime coercion ok: 2010-06-18T01:00:00
# Failed test 'pDateTime coercion ok: 2010-06-18T01:00:00'
# at t/coercions.t line 45.
# got: '1'
# expected: '0'
1..4
# Looks like you failed 1 test of 4.
Dubious, test returned 1 (wstat 256, 0x100)
Failed 1/4 subtests
Test Summary Report
-------------------
t/coercions.t (Wstat: 256 Tests: 4 Failed: 1)
Failed test: 4
Non-zero exit status: 1
Files=1, Tests=4, 0 wallclock secs ( 0.03 usr 0.00 sys + 0.35 cusr 0.02 csys = 0.40 CPU)
Result: FAIL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment