From 9e50f5e8c235fa3838cf4ce99090e8cae4ee4647 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 20 May 2010 15:45:28 -0700 Subject: [PATCH 01/22] Exception and class handling for getLastPost in the Thread. Update a test accordingly. --- lib/WebGUI/Asset/Post/Thread.pm | 12 ++++++------ t/Asset/Wobject/Collaboration/templateVariables.t | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/WebGUI/Asset/Post/Thread.pm b/lib/WebGUI/Asset/Post/Thread.pm index 1a6f11821..94dff5ba7 100644 --- a/lib/WebGUI/Asset/Post/Thread.pm +++ b/lib/WebGUI/Asset/Post/Thread.pm @@ -410,12 +410,12 @@ Fetches the last post in this thread, otherwise, returns itself. sub getLastPost { my $self = shift; my $lastPostId = $self->lastPostId; - my $lastPost; - if ($lastPostId) { - $lastPost = WebGUI::Asset::Post->newById($self->session, $lastPostId); - } - return $lastPost if (defined $lastPost); - return $self; + return $self unless $lastPostId; + my $lastPost = eval { WebGUI::Asset->newById($self->session, $lastPostId); }; + if (Exception::Class->caught()) { + return $self; + } + return $lastPost; } #------------------------------------------------------------------- diff --git a/t/Asset/Wobject/Collaboration/templateVariables.t b/t/Asset/Wobject/Collaboration/templateVariables.t index e151cec43..10ff8a086 100644 --- a/t/Asset/Wobject/Collaboration/templateVariables.t +++ b/t/Asset/Wobject/Collaboration/templateVariables.t @@ -89,7 +89,7 @@ ok( !$posts->[0]->{'user.isVisitor'}, 'first post made by visitor'); ok( $posts->[0]->{'hideProfileUrl'}, 'hide profile url, and user is visitor'); ok( !$posts->[0]->{'lastReply.user.isVisitor'}, 'lastReply not made by visitor'); ok( $posts->[0]->{'lastReply.hideProfileUrl'}, 'lastReply hide profile url, since user is visitor'); -is( $posts->[0]->{'lastReply.url'}, $threads[1]->getUrl.'?pn=1#id'.$threads[1]->getId, 'lastReply url has a query fragment prefixed by "id"'); +is( $posts->[0]->{'lastReply.url'}, $threads[1]->getUrl.'#id'.$threads[1]->getId, 'lastReply url has a query fragment prefixed by "id"'); is( $posts->[0]->{'url'}, $threads[1]->getUrl.'#id'.$threads[1]->getId, 'url has a query fragment prefixed by "id"'); From 42015a38c0233cc23542c78f238257302bd3d3b5 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 20 May 2010 16:05:58 -0700 Subject: [PATCH 02/22] Update the test to ignore the old database column, and to add new properties returned by get. --- t/Asset/Wobject/EventManagementSystem.t | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/t/Asset/Wobject/EventManagementSystem.t b/t/Asset/Wobject/EventManagementSystem.t index 10341bd7c..204bce789 100644 --- a/t/Asset/Wobject/EventManagementSystem.t +++ b/t/Asset/Wobject/EventManagementSystem.t @@ -310,7 +310,6 @@ $templateMock->mock('process', sub { $templateVars = $_[1]; } ); 'stateChangedBy' => ignore(), 'lineage' => ignore(), 'className' => 'WebGUI::Asset::Wobject::EventManagementSystem', - 'groupToApproveEvents' => ignore(), 'lastModified' => ignore(), 'title' => 'Test EMS', 'groupIdView' => ignore(), @@ -346,6 +345,9 @@ $templateMock->mock('process', sub { $templateVars = $_[1]; } ); 'eventSubmissionQueueTemplateId' => ignore(), 'eventSubmissionTemplateId' => ignore(), 'submittedLocationsList' => ignore(), + 'keywords' => ignore(), + 'session' => ignore(), + 'uiLevel' => ignore(), 'tickets_loop' => \@ticketArray, }, "www_printRemainingTickets: template variables valid" From dab177324d4c889d781adcb2a0caa9e3b2270ce6 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 13:37:06 -0700 Subject: [PATCH 03/22] Change from encode/decode to to/from in JSON, and call them explicitly. Exception handling for AJAX methods in the GalleryAlbum. --- lib/WebGUI/Asset/Wobject/GalleryAlbum.pm | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm b/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm index b2fc69c27..325049eff 100644 --- a/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm +++ b/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm @@ -47,7 +47,7 @@ use Carp qw( croak ); use File::Find; use File::Spec; use File::Temp qw{ tempdir }; -use JSON (); +use JSON qw(); use WebGUI::International; use WebGUI::HTML; use WebGUI::ProgressBar; @@ -1171,7 +1171,7 @@ sub www_ajax { my $result; # Get arguments encoded in json format - my $args = decode_json($form->get("args")); + my $args = JSON::from_json($form->get("args")); # Log some debug information $session->log->debug("Ajax service called with args=" . $form->get("args")); @@ -1198,7 +1198,7 @@ sub www_ajax { $result->{ err } = -1 if $result->{ errMessage }; # Return results encoded in json format - return encode_json( $result ); + return JSON::to_json( $result ); } @@ -1266,10 +1266,10 @@ sub _moveFileAjaxRequest { # Instantiate file with ID in before/after argument $destId = $args->{before} ? $args->{before} : $args->{after}; - $dest = WebGUI::Asset->newById( $session, $destId ); + $dest = eval { WebGUI::Asset->newById( $session, $destId ); }; # Return if destination file could not be instantiated - if ( Expeption::Class->caught() ) { + if ( Exception::Class->caught() ) { $session->log->error("Couldn't move file '$targetId' before/after file '$destId' because we couldn't instantiate the latter."); $result{ errMessage } = "ID in before/after argument seems to be invalid."; return \%result; From c56d2b9403556cdcdc8a814c075bcb55df6514ee Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 13:37:42 -0700 Subject: [PATCH 04/22] Fix some Gallery and GalleryAlbum tests. --- t/Asset/Wobject/Gallery/00base.t | 15 ++++----------- t/Asset/Wobject/GalleryAlbum/00base.t | 14 +++----------- t/Asset/Wobject/GalleryAlbum/ajax.t | 11 +++-------- 3 files changed, 10 insertions(+), 30 deletions(-) diff --git a/t/Asset/Wobject/Gallery/00base.t b/t/Asset/Wobject/Gallery/00base.t index bdce13580..bb1d380c8 100644 --- a/t/Asset/Wobject/Gallery/00base.t +++ b/t/Asset/Wobject/Gallery/00base.t @@ -40,6 +40,8 @@ my $gallery }); $versionTag->commit; +WebGUI::Test->addToCleanup($versionTag); +$gallery->cloneFromDb; is( Scalar::Util::blessed($gallery), "WebGUI::Asset::Wobject::Gallery", @@ -61,14 +63,5 @@ isa_ok( my $properties = $gallery->get; $gallery->purge; -is( - WebGUI::Asset->newById($session, $properties->{assetId}), undef, - "Gallery no longer able to be instanciated", -); - - -#---------------------------------------------------------------------------- -# Cleanup -END { - $versionTag->rollback(); -} +eval { WebGUI::Asset->newById($session, $properties->{assetId}); }; +ok( Exception::Class->caught(), 'Gallery no longer able to be instanciated after purge'); diff --git a/t/Asset/Wobject/GalleryAlbum/00base.t b/t/Asset/Wobject/GalleryAlbum/00base.t index 8414f54d5..88827f0ab 100644 --- a/t/Asset/Wobject/GalleryAlbum/00base.t +++ b/t/Asset/Wobject/GalleryAlbum/00base.t @@ -51,6 +51,7 @@ my $album }); $versionTag->commit; +WebGUI::Test->addToCleanup($versionTag); is( Scalar::Util::blessed($album), "WebGUI::Asset::Wobject::GalleryAlbum", @@ -66,14 +67,5 @@ isa_ok( my $properties = $album->get; $album->purge; -is( - WebGUI::Asset->newById($session, $properties->{assetId}), undef, - "Album no longer able to be instanciated", -); - - -#---------------------------------------------------------------------------- -# Cleanup -END { - $versionTag->rollback(); -} +eval { WebGUI::Asset->newById($session, $properties->{assetId}); }; +ok( Exception::Class->caught(), 'Album no longer able to be instanciated'); diff --git a/t/Asset/Wobject/GalleryAlbum/ajax.t b/t/Asset/Wobject/GalleryAlbum/ajax.t index 679137595..718aff5f8 100644 --- a/t/Asset/Wobject/GalleryAlbum/ajax.t +++ b/t/Asset/Wobject/GalleryAlbum/ajax.t @@ -77,6 +77,7 @@ for (my $i = 0; $i < 5; $i++) # Commit all changes $versionTag->commit; +WebGUI::Test->addToCleanup($versionTag); # Make album default asset $session->asset( $album ); @@ -95,7 +96,7 @@ use_ok("WebGUI::Asset::Wobject::GalleryAlbum"); #---------------------------------------------------------------------------- # Test calling without arguments -diag("general testing"); +note("general testing"); # Provide no arguments at all $result = callAjaxService({ }); @@ -105,7 +106,7 @@ ok( $result->{ err } != 0 && $result->{ errMessage }, "Error after call without #---------------------------------------------------------------------------- # Test moveFile action with incomplete of invalid arguments -diag("moveFile action"); +note("moveFile action"); # Omit target $result = callAjaxService({ @@ -256,9 +257,3 @@ sub callAjaxService { # Call ajax service function and decode reply return decode_json( $album->www_ajax() ); } - -#---------------------------------------------------------------------------- -# Cleanup -END { - $versionTag->rollback(); -} From 9059cf5f3f8d7ae36ad76befb64ca9947bc308f9 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 13:58:07 -0700 Subject: [PATCH 05/22] Exception handling for finding children in AssetLineage. --- lib/WebGUI/AssetLineage.pm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/WebGUI/AssetLineage.pm b/lib/WebGUI/AssetLineage.pm index acc78da01..dea5c621a 100644 --- a/lib/WebGUI/AssetLineage.pm +++ b/lib/WebGUI/AssetLineage.pm @@ -275,7 +275,7 @@ sub getFirstChild { $assetLineage->{firstChild}{$self->getId} = $lineage; $self->session->stow->set("assetLineage", $assetLineage); } - $child = WebGUI::Asset->newByLineage($self->session,$lineage); + $child = eval { WebGUI::Asset->newByLineage($self->session,$lineage); }; $self->cacheChild(first => $child); } return $child; @@ -301,7 +301,7 @@ sub getLastChild { $assetLineage->{lastChild}{$self->getId} = $lineage; $self->session->stow->set("assetLineage", $assetLineage); } - $child = WebGUI::Asset->newByLineage($self->session,$lineage); + $child = eval { WebGUI::Asset->newByLineage($self->session,$lineage); }; $self->cacheChild(last => $child); } return $child; From bfbe11ae327bb935d06d58b9599c352f79e65e01 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 13:58:49 -0700 Subject: [PATCH 06/22] Cleanup, exception handling, fresh assets in GalleryAlbum/delete.t --- t/Asset/Wobject/GalleryAlbum/delete.t | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/t/Asset/Wobject/GalleryAlbum/delete.t b/t/Asset/Wobject/GalleryAlbum/delete.t index bd58e20bf..4faf371b6 100644 --- a/t/Asset/Wobject/GalleryAlbum/delete.t +++ b/t/Asset/Wobject/GalleryAlbum/delete.t @@ -49,6 +49,10 @@ my $album }); $versionTag->commit; +WebGUI::Test->addToCleanup($versionTag); +foreach my $asset ($gallery, $album) { + $asset = $asset->cloneFromDb; +} #---------------------------------------------------------------------------- # Tests @@ -95,15 +99,6 @@ $maker->prepare({ }); $maker->run; -is( - WebGUI::Asset->newById( $session, $assetId ), - undef, - "GalleryAlbum cannot be instanciated after www_deleteConfirm", -); +eval { WebGUI::Asset->newById( $session, $assetId ); }; +ok (Exception::Class->caught(), "GalleryAlbum cannot be instanciated after www_deleteConfirm"); - -#---------------------------------------------------------------------------- -# Cleanup -END { - $versionTag->rollback(); -} From bf268bc66be8df71501e6f03582ca6301f72c989 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 15:05:00 -0700 Subject: [PATCH 07/22] Fix the canEdit method in the Matrix. --- lib/WebGUI/Asset/Wobject/Matrix.pm | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/lib/WebGUI/Asset/Wobject/Matrix.pm b/lib/WebGUI/Asset/Wobject/Matrix.pm index d9140b4a0..f151752c9 100644 --- a/lib/WebGUI/Asset/Wobject/Matrix.pm +++ b/lib/WebGUI/Asset/Wobject/Matrix.pm @@ -265,8 +265,7 @@ part of the C group. =cut -sub canEdit { - my $orig = shift; +override canEdit => sub { my $self = shift; my $userId = shift || $self->session->user->userId; @@ -276,14 +275,8 @@ sub canEdit { && $form->get( 'class' )->isa( 'WebGUI::Asset::MatrixListing' ) ) { return $self->canAddMatrixListing(); } - else { - if ($userId eq $self->ownerUserId) { - return 1; - } - my $user = WebGUI::User->new($self->session, $userId); - return $user->isInGroup($self->groupIdEdit); - } -} + return super(); +}; #------------------------------------------------------------------- From 2aff621168182d3f3b515ef876f33edbdeda791b Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 15:05:18 -0700 Subject: [PATCH 08/22] Cache and data updates for the Matrix test. --- t/Asset/Wobject/Matrix.t | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/t/Asset/Wobject/Matrix.t b/t/Asset/Wobject/Matrix.t index 115841b59..d3d69a503 100644 --- a/t/Asset/Wobject/Matrix.t +++ b/t/Asset/Wobject/Matrix.t @@ -109,6 +109,7 @@ my $matrixListing = $matrix->addChild({className=>'WebGUI::Asset::MatrixListing' my $secondVersionTag = WebGUI::VersionTag->new($session,$matrixListing->get("tagId")); $secondVersionTag->commit; WebGUI::Test->tagsToRollback($secondVersionTag); +$matrixListing = $matrixListing->cloneFromDb; # Test for sane object type isa_ok($matrixListing, 'WebGUI::Asset::MatrixListing'); @@ -155,7 +156,7 @@ cmp_deeply( # Test Listings Caching -my $listingsEncoded = WebGUI::Cache->new($session,"matrixListings_".$matrix->getId)->get; +my $listingsEncoded = $session->cache->get("matrixListings_".$matrix->getId); $listings = JSON->new->decode($listingsEncoded); cmp_deeply( @@ -229,9 +230,9 @@ cmp_deeply( # Test statistics caching by view method -WebGUI::Cache->new($session,"matrixStatistics_".$matrix->getId)->delete; +$session->cache->remove("matrixStatistics_".$matrix->getId); $matrix->view; -my $varStatisticsEncoded = WebGUI::Cache->new($session,"matrixStatistics_".$matrix->getId)->get; +my $varStatisticsEncoded = $session->cache->get("matrixStatistics_".$matrix->getId); my $varStatistics = JSON->new->decode($varStatisticsEncoded); cmp_deeply( @@ -302,9 +303,9 @@ $matrixListing->setRatings({category1=>'1',category2=>'9'}); $matrixListing->setRatings({category1=>'3',category2=>'5'}); $matrixListing->setRatings({category1=>'1',category2=>'9'}); -WebGUI::Cache->new($session,"matrixStatistics_".$matrix->getId)->delete; +$session->cache->remove("matrixStatistics_".$matrix->getId); $matrix->view; -my $varStatisticsEncoded = WebGUI::Cache->new($session,"matrixStatistics_".$matrix->getId)->get; +my $varStatisticsEncoded = $session->cache->get("matrixStatistics_".$matrix->getId); my $varStatistics = JSON->new->decode($varStatisticsEncoded); cmp_deeply( @@ -349,10 +350,10 @@ cmp_deeply( 'With only 9 ratings, still no statistics' ); -WebGUI::Cache->new($session,"matrixStatistics_".$matrix->getId)->delete; +$session->cache->remove("matrixStatistics_".$matrix->getId); $matrixListing->setRatings({category1=>'3'}); $matrix->view; -my $varStatisticsEncoded = WebGUI::Cache->new($session,"matrixStatistics_".$matrix->getId)->get; +my $varStatisticsEncoded = $session->cache->get("matrixStatistics_".$matrix->getId); my $varStatistics = JSON->new->decode($varStatisticsEncoded); cmp_deeply( @@ -364,7 +365,7 @@ cmp_deeply( best_rating_loop => [{ url => '/'.$matrixListing->get('url'), category=> 'category1', - name => 'untitled', + name => 'Untitled', mean => 2, median => 3, count => 10, @@ -380,7 +381,7 @@ cmp_deeply( worst_rating_loop => [{ url => '/'.$matrixListing->get('url'), category=> 'category1', - name => 'untitled', + name => 'Untitled', mean => 2, median => 3, count => 10, @@ -397,10 +398,10 @@ cmp_deeply( 'statistics calculated for the category with 10 ratings' ); -WebGUI::Cache->new($session,"matrixStatistics_".$matrix->getId)->delete; +$session->cache->remove("matrixStatistics_".$matrix->getId); $matrixListing->setRatings({category2=>'5'}); $matrix->view; -my $varStatisticsEncoded = WebGUI::Cache->new($session,"matrixStatistics_".$matrix->getId)->get; +my $varStatisticsEncoded = $session->cache->get("matrixStatistics_".$matrix->getId); my $varStatistics = JSON->new->decode($varStatisticsEncoded); cmp_deeply( @@ -412,7 +413,7 @@ cmp_deeply( best_rating_loop => [{ url => '/'.$matrixListing->get('url'), category=> 'category1', - name => 'untitled', + name => 'Untitled', mean => 2, median => 3, count => 10, @@ -420,7 +421,7 @@ cmp_deeply( { url => '/'.$matrixListing->get('url'), category=> 'category2', - name => 'untitled', + name => 'Untitled', mean => 7, median => 9, count => 10, @@ -428,7 +429,7 @@ cmp_deeply( worst_rating_loop => [{ url => '/'.$matrixListing->get('url'), category=> 'category1', - name => 'untitled', + name => 'Untitled', mean => 2, median => 3, count => 10, @@ -436,7 +437,7 @@ cmp_deeply( { url => '/'.$matrixListing->get('url'), category=> 'category2', - name => 'untitled', + name => 'Untitled', mean => 7, median => 9, count => 10, From 74c6f50bd213030b1efe3ee876818b10884358d1 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 18:32:43 -0700 Subject: [PATCH 09/22] Document init_meta in POD (I hope). --- lib/WebGUI/Definition/Asset.pm | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/lib/WebGUI/Definition/Asset.pm b/lib/WebGUI/Definition/Asset.pm index c6ae05a29..451d37a07 100644 --- a/lib/WebGUI/Definition/Asset.pm +++ b/lib/WebGUI/Definition/Asset.pm @@ -73,6 +73,20 @@ sub import { return 1; } +#------------------------------------------------------------------- + +=head2 init_meta ( ) + +A custom init_meta, so that if inported into a class, it applies the roles +to the class, and applies the meta-role to the meta-class. + +But, if it is applied to a Role, then only the meta-role is applied, since we want +the final application to be in the end user of the Role. + +This permits using this to compose Asset Roles with their own database tables. + +=cut + sub init_meta { my $class = shift; my %args = @_; From a4dd6f136245d3eebe73c880cf3b0b6877a541d0 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 18:39:36 -0700 Subject: [PATCH 10/22] POD for WebGUI::Types --- lib/WebGUI/Types.pm | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/lib/WebGUI/Types.pm b/lib/WebGUI/Types.pm index 6153656a5..9be43a946 100644 --- a/lib/WebGUI/Types.pm +++ b/lib/WebGUI/Types.pm @@ -1,8 +1,49 @@ package WebGUI::Types; +=head1 LEGAL + + ------------------------------------------------------------------- + WebGUI is Copyright 2001-2009 Plain Black Corporation. + ------------------------------------------------------------------- + Please read the legal notices (docs/legal.txt) and the license + (docs/license.txt) that came with this distribution before using + this software. + ------------------------------------------------------------------- + http://www.plainblack.com info@plainblack.com + ------------------------------------------------------------------- + +=cut + + use Moose; use Moose::Util::TypeConstraints; +=head1 NAME + +Package WebGUI::Types + +=head1 DESCRIPTION + +A package to hold all Moose types for WebGUI::Definition based classes. + +=head1 SYNOPSIS + +use WebGUI::Types; + +=head1 METHODS + +These types are provided by this class: + +=head2 WebGUI::Type::JSONArray + +The JSONArray is an subtype of ArrayRef, with coercions. If a string is applied to the property +with this type, it ties to pass it through JSON::from_json. If that fails, then it returns an +empty arrayref. + +Similarly, if an undef value is applied, it is coerced into an empty arrayref. + +=cut + subtype 'WebGUI::Type::JSONArray' => as 'ArrayRef' ; From 3870aea52616324101adbf4e2719778b23fa3701 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 19:15:22 -0700 Subject: [PATCH 11/22] Remove deprecated methods in SyndicatedContent. --- lib/WebGUI/Asset/Wobject/SyndicatedContent.pm | 52 ------------------- 1 file changed, 52 deletions(-) diff --git a/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm b/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm index afaab1a20..d791d4869 100644 --- a/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm +++ b/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm @@ -365,58 +365,6 @@ sub www_view { $self->next::method(@_); } -#------------------------------------------------------------------- - -=head2 www_viewRSS090 ( ) - -Deprecated. Use www_viewRss() instead. - -=cut - -sub www_viewRSS090 { - my $self = shift; - return $self->www_viewRss; -} - -#------------------------------------------------------------------- - -=head2 www_viewRSS091 ( ) - -Deprecated. Use www_viewRss() instead. - -=cut - -sub www_viewRSS091 { - my $self = shift; - return $self->www_viewRss; -} - -#------------------------------------------------------------------- - -=head2 www_viewRSS10 ( ) - -Deprecated. Use www_viewRdf() instead. - -=cut - -sub www_viewRSS10 { - my $self = shift; - return $self->www_viewRdf; -} - -#------------------------------------------------------------------- - -=head2 www_viewRSS20 ( ) - -Deprecated. Use www_viewRss() instead. - -=cut - -sub www_viewRSS20 { - my $self = shift; - return $self->www_viewRss; -} - __PACKAGE__->meta->make_immutable; 1; From 3faacabed2df340ac7e7ab5d75398aaa65280f2f Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 19:26:07 -0700 Subject: [PATCH 12/22] Change prepareView to use around instead of override, so it can work with packages that also need to wrap prepareView. --- lib/WebGUI/Role/Asset/RssFeed.pm | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/WebGUI/Role/Asset/RssFeed.pm b/lib/WebGUI/Role/Asset/RssFeed.pm index b7e8804dd..c3c6216b8 100644 --- a/lib/WebGUI/Role/Asset/RssFeed.pm +++ b/lib/WebGUI/Role/Asset/RssFeed.pm @@ -479,10 +479,11 @@ Extend the master class to insert head links via addHeaderLinks. =cut -override prepareView => sub { +around prepareView => sub { + my $orig = shift; my $self = shift; $self->addHeaderLinks; - return super(); + return $self->$orig; }; #------------------------------------------------------------------- From 0fac75759e52a8f435cca744c687c8cb2baa4ab3 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 19:26:55 -0700 Subject: [PATCH 13/22] Actually build an array of items in getRssFeedItems. Fix several method modifiers. --- lib/WebGUI/Asset/Wobject/SyndicatedContent.pm | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm b/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm index d791d4869..785bc5d79 100644 --- a/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm +++ b/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm @@ -217,6 +217,7 @@ sub getRssFeedItems { author => $item->author, guid => $item->guid, ); + push @items, \%feed_item; } return \@items; } @@ -294,11 +295,12 @@ See WebGUI::Asset::prepareView() for details. =cut -sub prepareView { +around prepareView => sub { + my $orig = shift; my $self = shift; - $self->next::method; - my $template = WebGUI::Asset::Template->newById($self->session, $self->templateId); - if (!$template) { + $self->$orig(); + my $template = eval { WebGUI::Asset->newById($self->session, $self->templateId); }; + if (Exception::Class->caught()) { WebGUI::Error::ObjectNotFound::Template->throw( error => qq{Template not found}, templateId => $self->templateId, @@ -307,7 +309,7 @@ sub prepareView { } $template->prepare($self->getMetaDataAsTemplateVariables); $self->{_viewTemplate} = $template; -} +}; #------------------------------------------------------------------- @@ -359,11 +361,11 @@ See WebGUI::Asset::Wobject::www_view() for details. =cut -sub www_view { - my $self = shift; - $self->session->http->setCacheControl($self->cacheTimeout); - $self->next::method(@_); -} +override www_view => sub { + my $self = shift; + $self->session->http->setCacheControl($self->cacheTimeout); + super(); +}; __PACKAGE__->meta->make_immutable; 1; From d88926c1ef1a16e5ed7a0af71fd2e3c0da136451 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 19:44:00 -0700 Subject: [PATCH 14/22] Update cache keys for SyndicatedContent in test. --- t/Asset/Wobject/SyndicatedContent.t | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/t/Asset/Wobject/SyndicatedContent.t b/t/Asset/Wobject/SyndicatedContent.t index 232264dd0..81a869d35 100644 --- a/t/Asset/Wobject/SyndicatedContent.t +++ b/t/Asset/Wobject/SyndicatedContent.t @@ -156,7 +156,7 @@ open my $rssFile, '<', WebGUI::Test->getTestCollateralPath('tbb.rss') or die "Unable to get RSS file"; my $rssContent = do { local $/; <$rssFile>; }; close $rssFile; -$session->cache->set($tbbUrl.'RSS', $rssContent, 60); +$session->cache->set($tbbUrl, $rssContent, 60); my $filteredFeed = $syndicated_content->generateFeed(); @@ -170,7 +170,7 @@ cmp_deeply( 'generateFeed: filters items based on the terms being in title, or description' ); -$session->cache->clear; +$session->cache->remove($tbbUrl); #################################################################### # @@ -191,13 +191,12 @@ open my $rssFile, '<', WebGUI::Test->getTestCollateralPath('oncp.xml') or die "Unable to get RSS file: oncp.xml"; my $rssContent = do { local $/; <$rssFile>; }; close $rssFile; -$session->cache->set($oncpUrl.'RSS', $rssContent, 60); +$session->cache->set($oncpUrl, $rssContent, 60); my $oddFeed1 = $syndicated_content->generateFeed(); my @oddItems = $oddFeed1->get_item(); is (@oddItems, 13, 'feed has items even without pubDates or links'); -$session->cache->clear; - +$session->cache->remove($oncpUrl); From b3a684730bab94bb644559af97b51b5782adf7f3 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 21 May 2010 19:55:34 -0700 Subject: [PATCH 15/22] Prune out duplicate tests. --- t/Asset/permissions.t | 716 +----------------------------------------- 1 file changed, 1 insertion(+), 715 deletions(-) diff --git a/t/Asset/permissions.t b/t/Asset/permissions.t index e2972ef42..8add65c2c 100644 --- a/t/Asset/permissions.t +++ b/t/Asset/permissions.t @@ -33,8 +33,6 @@ use Storable qw/dclone/; my $session = WebGUI::Test->session; -my @getTitleTests = getTitleTests($session); - my $rootAsset = WebGUI::Asset->getRoot($session); ##Test users. @@ -151,340 +149,12 @@ $canViewMaker->prepare( }, ); -plan tests => 114 - + 2*scalar(@getTitleTests) #same tests used for getTitle and getMenuTitle - + $canAddMaker->plan +plan tests => $canAddMaker->plan + $canAddMaker2->plan + $canEditMaker->plan + $canViewMaker->plan ; -note "loadModule"; -{ - my $className = eval { WebGUI::Asset->loadModule('Moose::Asset'); }; - my $e = Exception::Class->caught; - isa_ok($e, 'WebGUI::Error::InvalidParam', 'loadModule must get a WebGUI::Asset class'); - cmp_deeply( - $e, - methods( - error => 'Not a WebGUI::Asset class', - param => 'Moose::Asset', - ), - '... checking error message', - ); -} - -# Test the default constructor -my $defaultAsset = WebGUI::Asset->getDefault($session); -is($defaultAsset, 'WebGUI::Asset::Wobject::Layout'); - -# Test the new constructor -my $assetId = "PBnav00000000000000001"; # one of the default nav assets - -# - explicit class -my $asset = WebGUI::Asset->newById($session, $assetId); -isa_ok ($asset, 'WebGUI::Asset::Wobject::Navigation'); -is ($asset->getId, $assetId, 'new constructor explicit - returns correct asset'); - -# - new by hashref properties -$asset = undef; -$asset = WebGUI::Asset->newByPropertyHashRef($session, { - className=>"WebGUI::Asset::Wobject::Navigation", - assetId=>$assetId - }); -isa_ok ($asset, 'WebGUI::Asset::Wobject::Navigation'); -is ($asset->getId, $assetId, 'new constructor newByHashref - returns correct asset'); - -# - implicit class -$asset = undef; -$asset = WebGUI::Asset::Wobject::Navigation->new($session, $assetId); -isa_ok ($asset, 'WebGUI::Asset::Wobject::Navigation'); -is ($asset->getId, $assetId, 'new constructor implicit - returns correct asset'); - -# - die gracefully -# -- no asset id -note "new, constructor fails"; -{ - my $deadAsset = eval { WebGUI::Asset->new($session, ''); }; - my $e = Exception::Class->caught; - isa_ok($e, 'WebGUI::Error::InvalidParam', 'new must get an assetId'); - cmp_deeply( - $e, - methods( - error => 'Asset constructor new() requires an assetId.', - ), - '... checking error message', - ); -} - -# -- no class -my $primevalAsset = WebGUI::Asset->new($session, $assetId); -isa_ok ($primevalAsset, 'WebGUI::Asset'); - -# Test the newById Constructor -$asset = undef; - -note "new"; -use WebGUI::Asset::Wobject::Navigation; -$asset = WebGUI::Asset::Wobject::Navigation->new($session, $assetId); -isa_ok ($asset, 'WebGUI::Asset::Wobject::Navigation'); -is ($asset->getId, $assetId, 'new constructor - returns correct asset when invoked with correct class'); - -note "getClassById"; -{ - my $deadAsset = eval { WebGUI::Asset->getClassById($session, 'RoysNonExistantAssetId'); }; - my $e = Exception::Class->caught; - isa_ok($e, 'WebGUI::Error::InvalidParam', 'getClassById must have a valid assetId'); - cmp_deeply( - $e, - methods( - error => "Couldn't lookup classname", - param => 'RoysNonExistantAssetId', - ), - '... checking error message', - ); -} - -note "newById"; -{ - my $deadAsset = eval { WebGUI::Asset->newById($session); }; - my $e = Exception::Class->caught; - isa_ok($e, 'WebGUI::Error::InvalidParam', "newById won't work without an assetId"); - cmp_deeply( - $e, - methods( - error => "newById must get an assetId", - ), - '... checking error message', - ); -} - -# -- no session -# Root Asset -isa_ok($rootAsset, 'WebGUI::Asset'); -is($rootAsset->getId, 'PBasset000000000000001', 'Root Asset ID check'); - -# getMedia Constructor - -my $mediaFolder = WebGUI::Asset->getMedia($session); -isa_ok($mediaFolder, 'WebGUI::Asset::Wobject::Folder'); -is($mediaFolder->getId, 'PBasset000000000000003', 'Media Folder Asset ID check'); - -# getImportNode Constructor - -my $importNode = WebGUI::Asset->getImportNode($session); -isa_ok($importNode, 'WebGUI::Asset::Wobject::Folder'); -is($importNode->getId, 'PBasset000000000000002', 'Import Node Asset ID check'); -is($importNode->getParent->getId, $rootAsset->getId, 'Import Nodes parent is Root Asset'); - -# tempspace Constructor - -my $tempNode = WebGUI::Asset->getTempspace($session); -isa_ok($tempNode, 'WebGUI::Asset::Wobject::Folder'); -is($tempNode->getId, 'tempspace0000000000000', 'Tempspace Asset ID check'); -is($tempNode->getParent->getId, $rootAsset->getId, 'Tempspace parent is Root Asset'); - -################################################################ -# -# urlExists -# -################################################################ - -##We need an asset with a URL for this one. - -my $importUrl = $importNode->get('url'); -my $importId = $importNode->getId; - -ok( WebGUI::Asset->urlExists($session, $importUrl), 'url for import node exists'); -ok( WebGUI::Asset->urlExists($session, uc($importUrl)), 'url for import node exists, case insensitive'); -ok( !WebGUI::Asset->urlExists($session, '/foo/bar/baz'), 'made up url does not exist'); - -ok( !WebGUI::Asset->urlExists($session, $importUrl, {assetId => $importId}), 'url for import node only exists at specific id'); -ok( !WebGUI::Asset->urlExists($session, '/foo/bar/baz', {assetId => $importId}), 'imaginary url does not exist at specific id'); -ok( WebGUI::Asset->urlExists($session, $importUrl, {assetId => 'notAnWebGUIId'}), 'imaginary url does not exist at wrong id'); - -################################################################ -# -# addEditLabel -# -################################################################ - -my $i18n = WebGUI::International->new($session, 'Asset_Wobject'); -is($importNode->addEditLabel, $i18n->get('edit').' '.$importNode->getName, 'addEditLabel, default mode is edit mode'); - -my $origRequest = $session->{_request}; -my $newRequest = Test::MockObject->new(); -my $func; -$newRequest->set_bound('body', \$func); -$newRequest->set_bound('param', \$func); -$session->{_request} = $newRequest; -$func = 'add'; -is($importNode->addEditLabel, $i18n->get('add').' '.$importNode->getName, 'addEditLabel, use add mode'); -$session->{_request} = $origRequest; - -################################################################ -# -# fixUrl -# -################################################################ - -my $versionTag = WebGUI::VersionTag->getWorking($session); -WebGUI::Test->tagsToRollback($versionTag); -$versionTag->set({name=>"Asset tests"}); - -$properties = { - # '1234567890123456789012' - id => 'fixUrlAsset00000000012', - title => 'fixUrl Asset Test', - className => 'WebGUI::Asset::Wobject::Folder', - url => 'fixUrlFolderURL2', -}; - -my $fixUrlAsset = $defaultAsset->addChild($properties, $properties->{id}); - -# '1234567890123456789012' -$properties->{id} = 'fixUrlAsset00000000013'; -$properties->{url} = 'fixUrlFolderURL9'; - -my $fixUrlAsset2 = $defaultAsset->addChild($properties, $properties->{id}); - -# '1234567890123456789012' -$properties->{id} = 'fixUrlAsset00000000014'; -$properties->{url} = 'fixUrlFolderURL00'; - -my $fixUrlAsset3 = $defaultAsset->addChild($properties, $properties->{id}); - -# '1234567890123456789012' -$properties->{id} = 'fixUrlAsset00000000015'; -$properties->{url} = 'fixUrlFolderURL100'; - -my $fixUrlAsset4 = $defaultAsset->addChild($properties, $properties->{id}); -is($fixUrlAsset4->get('url'), 'fixurlfolderurl100', 'asset setup correctly for 100->101 test'); - -delete $properties->{url}; -# '1234567890123456789012' -$properties->{id} = 'fixUrlAsset00000000016'; -$properties->{menuTitle} = 'fix url folder url autogenerated'; - -my $fixUrlAsset5 = $defaultAsset->addChild($properties, $properties->{id}); - -my $properties2 = { - # '1234567890123456789012' - id => 'fixTitleAsset000000010', - title => '', - className => 'WebGUI::Asset::Snippet', - url => 'fixTitleAsset1', -}; - -my $fixTitleAsset = $defaultAsset->addChild($properties2, $properties2->{id}); -##Commit this asset right away -$fixTitleAsset->commit; - -$properties2 = { - # '1234567890123456789012' - id => 'getTitleAsset000000010', - title => '', - className => 'WebGUI::Asset::Snippet', - url => 'getTitleAsset1', -}; - -my $getTitleAsset = $defaultAsset->addChild($properties2, $properties2->{id}); -$getTitleAsset->commit; - -$versionTag->commit; - -$session->setting->set('urlExtension', undef); - -is($importNode->fixUrl('1234'.'-'x235 . 'abcdefghij'), '1234'.'-'x235 . 'abcdefghij', 'fixUrl leaves long URLs under 250 characters alone'); -is($importNode->fixUrl('1234'.'-'x250 . 'abcdefghij'), '1234'.'-'x216, 'fixUrl truncates long URLs over 250 characters to 220 characters'); - -WebGUI::Test->originalConfig('extrasURL'); -WebGUI::Test->originalConfig('uploadsURL'); -WebGUI::Test->originalConfig('assets'); - -$session->config->set('extrasURL', '/extras'); -$session->config->set('uploadsURL', '/uploads'); - -is($importNode->fixUrl('/extras'), '_extras', 'underscore prepended to URLs that match the extrasURL'); -is($importNode->fixUrl('/uploads'), '_uploads', 'underscore prepended to URLs that match the uploadsURL'); - -#Now that we have verified that extrasURL and uploadsURL both work, just test one. -$session->config->set('extrasURL', '/extras1/'); -is($importNode->fixUrl('/extras1'), '_extras1', 'trailing underscore in extrasURL does not defeat the check'); - -$session->config->set('extrasURL', 'http://mysite.com/extras2'); -is($importNode->fixUrl('/extras2'), '_extras2', 'underscore prepended to URLs that match the extrasURL, even with http://'); - -##Now, check extension removal - -is($importNode->fixUrl('one.html/two.html'), 'one/two.html', 'extensions are not allowed higher up in the path'); -is($importNode->fixUrl('one.html/two.html/three.html'), 'one/two/three.html', 'extensions are not allowed anywhere in the path'); -is($importNode->fixUrl('one.one.html/two.html/three.html'), 'one/two/three.html', 'multiple dot extensions are removed in any path element'); -is($importNode->fixUrl('.startsWithDot'), '.startswithdot', 'leading dots are okay'); - -##Now, check duplicate URLs - -is($importNode->fixUrl('/rootyRootRoot'), 'rootyrootroot', 'URLs are lowercased'); -is($importNode->fixUrl('/root'), 'root2', 'If a node exists, appends a "2" to it'); -my $importNodeURL = $importNode->getUrl; -$importNodeURL =~ s{ ^ / }{}x; -is($importNode->fixUrl($importNodeURL), $importNodeURL, q{fixing an asset's own URL returns it unchanged}); - -is($importNode->fixUrl('fixUrlFolderURL2'), 'fixurlfolderurl3', 'if a URL exists, fix it by incrementing any ending digits 2 -> 3'); -is($importNode->fixUrl('fixUrlFolderURL9'), 'fixurlfolderurl10', 'increments past single digits 9 -> 10'); -is($importNode->fixUrl('fixUrlFolderURL00'), 'fixurlfolderurl1', 'initial zeroes are not preserved 00 -> 1'); -is($importNode->fixUrl('fixUrlFolderURL100'), 'fixurlfolderurl101', '100->101'); - -is($fixUrlAsset5->fixUrl(), 'home/fix-url-folder-url-autogenerated', 'fixUrl will autogenerate a url if not provided one'); - -# Automatic extension adding -$session->setting->set('urlExtension', 'html'); -is($importNode->fixUrl('fixurl'), 'fixurl.html', 'Automatic adding of extensions works'); -is($importNode->fixUrl('fixurl.css'), 'fixurl.css', 'extensions aren\'t automatically added if there is already and extension'); -$session->setting->set('urlExtension', undef); - - -################################################################ -# -# getTitle -# getMenuTitle -# -################################################################ - -my $getTitleAssetName = $getTitleAsset->getName(); - -foreach my $test (@getTitleTests) { - my $expectedTitle = $test->{assetName} ? $getTitleAssetName : $test->{title}; - $getTitleAsset->update({ - title => $test->{title}, - menuTitle => $test->{title}, - }); - is($getTitleAsset->getTitle, $expectedTitle, $test->{comment}); - is($getTitleAsset->getMenuTitle, $expectedTitle, $test->{comment}); -} - -################################################################ -# -# getIcon -# -################################################################ - -like($importNode->getIcon, qr{folder.gif$}, 'getIcon gets correct icon for importNode'); -like($importNode->getIcon(1), qr{small/folder.gif$}, 'getIcon gets small icon for importNode'); - -my $extras = $session->config->get('extrasURL'); - -like($importNode->getIcon(), qr{$extras}, 'getIcon returns an icon from the extras URL'); - -like($defaultAsset->getIcon, qr{layout.gif$}, 'getIcon gets icon for a layout'); -like($fixTitleAsset->getIcon, qr{snippet.gif$}, 'getIcon gets icon for a snippet'); - - -TODO: { - local $TODO = "Coverage test"; - ok(0, "Test the default name for the icon, if not given in the definition sub"); -} - ################################################################ # # canAdd @@ -515,388 +185,4 @@ $canEditMaker->run; $canViewMaker->run; -################################################################ -# -# addMissing -# -################################################################ -$session->user({ userId => 3 }); -$session->var->switchAdminOff; -is($canEditAsset->addMissing('/nowhereMan'), undef, q{addMissing doesn't return anything unless use is in Admin Mode}); - -$session->var->switchAdminOn; -my $addMissing = $canEditAsset->addMissing('/nowhereMan'); -ok($addMissing, 'addMissing returns some output when in Admin Mode'); - -{ - - my $parser = HTML::TokeParser->new(\$addMissing); - my $link = $parser->get_tag('a'); - my $url = $link->[1]{'href'} || '-'; - like($url, qr{func=add;class=WebGUI::Asset::Wobject::Layout;url=/nowhereMan$}, 'addMissing: Link will add a new page asset with correct URL'); - -} - -################################################################ -# -# getContainer -# -################################################################ - -is($rootAsset->getContainer->getId, $rootAsset->getId, 'getContainer: A folder is a container, its container is itself'); -is($fixTitleAsset->getContainer->getId, $defaultAsset->getId, 'getContainer: A snippet is not a container, its container is its parent'); - -################################################################ -# -# getName -# -################################################################ - -is($fixTitleAsset->getName, $i18n->get('assetName', 'Asset_Snippet'), 'getName: Returns the internationalized name of the Asset, Snippet'); -is($importNode->getName, $i18n->get('assetName', 'Asset_Folder'), 'getName: Returns the internationalized name of the Asset, Folder'); -is($canEditAsset->getName, $i18n->get('asset', 'Asset'), 'getName: Returns the internationalized name of the Asset, core Asset'); - -################################################################ -# -# getToolbarState -# toggleToolbar -# -################################################################ - -is($getTitleAsset->getToolbarState, undef, 'getToolbarState: default toolbar state is undef'); -$getTitleAsset->toggleToolbar(); -is($getTitleAsset->getToolbarState, 1, 'getToolbarState: toggleToolbarState toggled the state to 1'); -$getTitleAsset->toggleToolbar(); -is($getTitleAsset->getToolbarState, 0, 'getToolbarState: toggleToolbarState toggled the state to 0'); - -################################################################ -# -# getUiLevel -# -################################################################ - -is($canEditAsset->getUiLevel, 1, 'getUiLevel: WebGUI::Asset uses the default uiLevel of 1'); -is($fixTitleAsset->getUiLevel, 5, 'getUiLevel: Snippet has an uiLevel of 5'); - -my $origAssetUiLevel = $session->config->get('assetUiLevel'); -$session->config->set('assets/WebGUI::Asset/uiLevel', 8); -$session->config->set('assets/WebGUI::Asset::Snippet/uiLevel', 8); - -is($canEditAsset->getUiLevel, 8, 'getUiLevel: WebGUI::Asset has a configured uiLevel of 8'); -is($fixTitleAsset->getUiLevel, 8, 'getUiLevel: Snippet has a configured uiLevel of 8'); - - -################################################################ -# -# isValidRssItem -# -################################################################ - -is($canViewAsset->isValidRssItem, 1, 'isValidRssItem: By default, all Assets are valid RSS items'); - -################################################################ -# -# getEditTabs -# -################################################################ - -my @tabs = $canViewAsset->getEditTabs; -is(scalar(@tabs), 4, 'getEditTabs: 4 tabs by default'); - -################################################################ -# -# getEditForm -# -################################################################ - -$session->style->sent(0); ##Prevent extra output from being generated by session->style - ##At some point, a test will need to tie STDOUT and make sure - ##that the output is correct. -isa_ok($canViewAsset->getEditForm, 'WebGUI::TabForm', 'getEditForm: Returns a tabForm'); - -TODO: { - local $TODO = 'More getEditForm tests'; - ok(0, 'Validate form output'); -} - -################################################################ -# -# newById -# -################################################################ - -my $newFixTitleAsset = WebGUI::Asset->newById($session, $fixTitleAsset->getId); -isnt($newFixTitleAsset, undef, 'newById did not fail'); -isa_ok($newFixTitleAsset, 'WebGUI::Asset', 'newById: able to look up an existing asset by id'); -cmp_deeply($newFixTitleAsset->{_properties}, $fixTitleAsset->{_properties}, 'newById created a duplicate asset'); - -################################################################ -# -# getNotFound -# -################################################################ - -my $origNotFoundPage = $session->setting->get('notFoundPage'); - -$session->setting->set('notFoundPage', WebGUI::Asset->getDefault($session)->getId); - -isa_ok(WebGUI::Asset->getNotFound($session), 'WebGUI::Asset', 'getNotFound: Returns an asset'); -is(WebGUI::Asset->getNotFound($session)->getId, WebGUI::Asset->getDefault($session)->getId, 'getNotFound: Returns the correct asset'); - -$session->setting->set('notFoundPage', $fixTitleAsset->getId); -is(WebGUI::Asset->getNotFound($session)->getId, $fixTitleAsset->getId, 'getNotFound: Returns the correct asset on a different asset'); - -$session->setting->set('notFoundPage', $origNotFoundPage); - -################################################################ -# -# isExportable -# -################################################################ -is($rootAsset->get('isExportable'), 1, 'isExportable exists, defaults to 1'); - -################################################################ -# -# getSeparator -# -################################################################ -is($rootAsset->getSeparator, '~~~PBasset000000000000001~~~', 'getSeparator, known assetId'); -is($rootAsset->getSeparator('!'), '!!!PBasset000000000000001!!!', 'getSeparator, given pad character'); -isnt($rootAsset->getSeparator, $mediaFolder->getSeparator, 'getSeparator: unique string'); - -################################################################ -# -# get -# -################################################################ -my $assetProps = $rootAsset->get(); -my $funkyTitle = q{Miss Annie's Whoopie Emporium and Sasparilla Shop}; -$assetProps->{title} = $funkyTitle; - -isnt( $rootAsset->get('title'), $funkyTitle, 'get returns a safe copy of the Asset properties'); - -################################################################ -# -# getIsa -# -################################################################ -my $node = WebGUI::Asset->getRoot($session); -my $product1 = $node->addChild({ className => 'WebGUI::Asset::Sku::Product'}); -my $product2 = $node->addChild({ className => 'WebGUI::Asset::Sku::Product'}); -my $product3 = $node->addChild({ className => 'WebGUI::Asset::Sku::Product'}); - -my $getAProduct = WebGUI::Asset::Sku::Product->getIsa($session); -isa_ok($getAProduct, 'CODE', 'getIsa returns a sub ref'); -my $counter = 0; -my $productIds = []; -while( my $product = $getAProduct->()) { - ++$counter; - push @{ $productIds }, $product->getId; -} -is($counter, 3, 'getIsa: returned only 3 Products'); -cmp_bag($productIds, [$product1->getId, $product2->getId, $product3->getId], 'getIsa returned the correct 3 products'); - -my $getASku = WebGUI::Asset::Sku->getIsa($session); -$counter = 0; -my $skuIds = []; -while( my $sku = $getASku->()) { - ++$counter; - push @{ $skuIds }, $sku->getId; -} -is($counter, 3, 'getIsa: returned only 3 Products for a parent class'); -cmp_bag($skuIds, [$product1->getId, $product2->getId, $product3->getId], 'getIsa returned the correct 3 products for a parent class'); - -$product1->purge; -$product2->purge; -$product3->purge; - -################################################################ -# -# inheritUrlFromParent -# -################################################################ - -my $versionTag4 = WebGUI::VersionTag->getWorking($session); -WebGUI::Test->tagsToRollback($versionTag4); -$versionTag4->set( { name => 'inheritUrlFromParent tests' } ); - -$properties = { - # '1234567890123456789012' - id => 'inheritUrlFromParent01', - title => 'inheritUrlFromParent01', - className => 'WebGUI::Asset::Wobject::Layout', - url => 'inheriturlfromparent01', -}; - -my $iufpAsset = $defaultAsset->addChild($properties, $properties->{id}); -$iufpAsset->commit; - -$properties2 = { - # '1234567890123456789012' - id => 'inheritUrlFromParent02', - title => 'inheritUrlFromParent02', - className => 'WebGUI::Asset::Wobject::Layout', - url => 'inheriturlfromparent02', -}; - -my $iufpAsset2 = $iufpAsset->addChild($properties2, $properties2->{id}); -$iufpAsset2->update( { inheritUrlFromParent => 1 } ); -$iufpAsset2->commit; -is($iufpAsset2->get('url'), 'inheriturlfromparent01/inheriturlfromparent02', 'inheritUrlFromParent works'); - -my $properties2a = { - # '1234567890123456789012' - id => 'inheritUrlFromParent2a', - title => 'inheritUrlFromParent2a', - className => 'WebGUI::Asset::Wobject::Layout', - url => 'inheriturlfromparent2a', - inheritUrlFromParent => 1, -}; - -my $iufpAsset2a = $iufpAsset->addChild($properties2a, $properties2a->{id}); -$iufpAsset2a->commit; -is($iufpAsset2a->get('url'), 'inheriturlfromparent01/inheriturlfromparent2a', '... works when created with the property'); - -# works for setting, now try disabling. Should not change the URL. -$iufpAsset2->update( { inheritUrlFromParent => 0 } ); -$iufpAsset2->commit; -is($iufpAsset2->get('url'), 'inheriturlfromparent01/inheriturlfromparent02', '... setting inheritUrlFromParent to 0 works'); - -# also make sure that it is actually disabled -is($iufpAsset2->get('inheritUrlFromParent'), 0, "... disabling inheritUrlFromParent actually works"); - -# works for setting and disabling, now ensure it recurses - -my $properties3 = { - # '1234567890123456789012' - id => 'inheritUrlFromParent03', - title => 'inheritUrlFromParent03', - className => 'WebGUI::Asset::Wobject::Layout', - url => 'inheriturlfromparent03', -}; -my $iufpAsset3 = $iufpAsset2->addChild($properties3, $properties3->{id}); -$iufpAsset3->commit; -$iufpAsset2->update( { inheritUrlFromParent => 1 } ); -$iufpAsset2->commit; -$iufpAsset3->update( { inheritUrlFromParent => 1 } ); -$iufpAsset3->commit; -is($iufpAsset3->get('url'), 'inheriturlfromparent01/inheriturlfromparent02/inheriturlfromparent03', '... recurses properly'); - -$iufpAsset2->update({url => 'iufp2'}); -is($iufpAsset2->get('url'), 'inheriturlfromparent01/iufp2', '... update works propertly when iUFP is not passed'); - - -################################################################ -# -# requestAutoCommit to move uncommitted child to uncommitted parent -# -################################################################ - -my $versionTag5 = WebGUI::VersionTag->getWorking($session); -WebGUI::Test->tagsToRollback($versionTag5); -$versionTag5->set( { name => 'move commit of child to uncommitted parent on requestAutoCommit tests vt1' } ); - -$properties = { - # '1234567890123456789012' - id => 'moveVersionToParent_01', - title => 'moveVersionToParent_01', - className => 'WebGUI::Asset::Wobject::Layout', - url => 'moveVersionToParent_01', -}; - -my $parentAsset = $defaultAsset->addChild($properties, $properties->{id}); -my $parentVersionTag = WebGUI::VersionTag->new($session, $parentAsset->get('tagId')); -is($parentVersionTag->get('isCommitted'),0, 'built non-committed parent asset'); - - -my $versionTag6 = WebGUI::VersionTag->create($session, {}); -WebGUI::Test->tagsToRollback($versionTag6); -$versionTag6->set( { name => 'move commit of child to uncommitted parent on requestAutoCommit tests vt2' } ); -$versionTag6->setWorking; - -$properties2 = { - # '1234567890123456789012' - id => 'moveVersionToParent_03', - title => 'moveVersionToParent_03', - className => 'WebGUI::Asset::Wobject::Layout', - url => 'moveVersionToParent_03', -}; - -my $childAsset = $parentAsset->addChild($properties, $properties2->{id}); -my $testAsset = WebGUI::Asset->newPending($session, $childAsset->get('parentId')); -my $testVersionTag = WebGUI::VersionTag->new($session, $testAsset->get('tagId')); - -my $childVersionTag; -$childVersionTag = WebGUI::VersionTag->new($session, $childAsset->get('tagId')); -is($childVersionTag->get('isCommitted'),0, 'built non-committed child asset'); - -isnt($testAsset->get('tagId'),$childAsset->get('tagId'),'parent asset and child asset have different version tags'); -isnt($testVersionTag->getId,$childVersionTag->getId,'parent asset and child asset version tags unmatched'); - -eval { - $childAsset->requestAutoCommit; - $childVersionTag = WebGUI::VersionTag->new($session, $childAsset->get('tagId')); -}; -is($childVersionTag->get('isCommitted'),0, 'confirm non-committed child asset'); - -is($testAsset->get('tagId'),$childAsset->get('tagId'),'parent asset and child asset have same version tags'); - -eval { - $testVersionTag->commit; -}; - -is($testVersionTag->get('isCommitted'),1,'parent asset is now committed'); - -$childVersionTag = WebGUI::VersionTag->new($session, $childAsset->get('tagId')); -is($childVersionTag->get('isCommitted'),1,'child asset is now committed'); - -################################################################ -# -# cloneFromDb -# -################################################################ - -my $assetToCommit = $defaultAsset->addChild({ className => 'WebGUI::Asset::Snippet', title => 'Snippet to commit and clone from db', }); -my $cloneTag = WebGUI::VersionTag->getWorking($session); -WebGUI::Test->tagsToRollback($cloneTag); -$cloneTag->commit; -is($assetToCommit->get('status'), 'pending', 'cloneFromDb: local asset is still pending'); -$assetToCommit = $assetToCommit->cloneFromDb; -is($assetToCommit->get('status'), 'approved', '... returns fresh, commited asset from the db'); - -##Return an array of hashrefs. Each hashref describes a test - -##Return an array of hashrefs. Each hashref describes a test -##for the getTitle and getMenuTitle tests. If "assetName" != 0, they -##will return the Asset's internationalized name. - -sub getTitleTests { - my $session = shift; - return ({ - title => undef, - assetName => 1, - comment => "getTitle: undef returns the Asset's name", - }, - { - title => '', - assetName => 1, - comment => "getTitle: null string returns the Asset's name", - }, - { - title => 'untitled', - assetName => 1, - comment => "getTitle: 'untitled' returns the Asset's name", - }, - { - title => 'UnTiTlEd', - assetName => 1, - comment => "getTitle: 'untitled' in any case returns the Asset's title", - }, - { - title => 'This is a good Title', - assetName => 0, - comment => "getTitle: Good titles are passed", - }, - ); -} From 5759620eb4ffc8c9062b77344b582a29db47c722 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sat, 22 May 2010 20:41:32 -0700 Subject: [PATCH 16/22] Add missing use line for Asset. --- lib/WebGUI/FilePump/Bundle.pm | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/WebGUI/FilePump/Bundle.pm b/lib/WebGUI/FilePump/Bundle.pm index 65f5afaf0..949859540 100644 --- a/lib/WebGUI/FilePump/Bundle.pm +++ b/lib/WebGUI/FilePump/Bundle.pm @@ -2,6 +2,7 @@ package WebGUI::FilePump::Bundle; use base qw/WebGUI::Crud WebGUI::JSONCollateral/; use strict; +use WebGUI::Asset; use WebGUI::International; use WebGUI::Exception; use WebGUI::Utility; From ae88345e045273b82dbbadc3d45260e84510a012 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sat, 22 May 2010 22:27:46 -0700 Subject: [PATCH 17/22] Revert the sense of the exception handling, to the right state. --- lib/WebGUI/Shop/TransactionItem.pm | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/WebGUI/Shop/TransactionItem.pm b/lib/WebGUI/Shop/TransactionItem.pm index 60c2a37c8..ffa57cb59 100644 --- a/lib/WebGUI/Shop/TransactionItem.pm +++ b/lib/WebGUI/Shop/TransactionItem.pm @@ -134,11 +134,11 @@ sub getSku { my ($self) = @_; my $asset = eval { WebGUI::Asset->newById($self->transaction->session, $self->get("assetId")); }; if (Exception::Class->caught()) { - $asset->applyOptions($self->get("options")); - return $asset; + WebGUI::Error::ObjectNotFound->throw(error=>'SKU Asset '.$self->get('assetId').' could not be instanciated. Perhaps it no longer exists.', id=>$self->get('assetId')); + return undef; } - WebGUI::Error::ObjectNotFound->throw(error=>'SKU Asset '.$self->get('assetId').' could not be instanciated. Perhaps it no longer exists.', id=>$self->get('assetId')); - return undef; + $asset->applyOptions($self->get("options")); + return $asset; } #------------------------------------------------------------------- From 095b7c7ef9287f373a8057f6d2c4f12d6683828a Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sat, 22 May 2010 22:38:32 -0700 Subject: [PATCH 18/22] Add missing use lines to ITransact. --- lib/WebGUI/Shop/PayDriver/ITransact.pm | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/WebGUI/Shop/PayDriver/ITransact.pm b/lib/WebGUI/Shop/PayDriver/ITransact.pm index 0209914bd..f19cca8e0 100644 --- a/lib/WebGUI/Shop/PayDriver/ITransact.pm +++ b/lib/WebGUI/Shop/PayDriver/ITransact.pm @@ -18,6 +18,8 @@ use strict; use XML::Simple; use Data::Dumper; use Tie::IxHash; +use LWP::UserAgent; +use HTTP::Request; use base qw/WebGUI::Shop::PayDriver/; From 59f8c0cea0178d250093a8f9969ec45eeb7381a4 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sat, 22 May 2010 22:48:42 -0700 Subject: [PATCH 19/22] Test cleanups. Drop use_ok, change order of cleanup. --- t/Shop/PayDriver/ITransact.t | 59 +++++++++++++++--------------------- 1 file changed, 24 insertions(+), 35 deletions(-) diff --git a/t/Shop/PayDriver/ITransact.t b/t/Shop/PayDriver/ITransact.t index 44dd2256c..028d1e356 100644 --- a/t/Shop/PayDriver/ITransact.t +++ b/t/Shop/PayDriver/ITransact.t @@ -25,6 +25,7 @@ use WebGUI::Shop::Ship; use WebGUI::Shop::Transaction; use JSON; use HTML::Form; +use WebGUI::Shop::PayDriver::ITransact; #---------------------------------------------------------------------------- # Init @@ -34,26 +35,12 @@ my $session = WebGUI::Test->session; #---------------------------------------------------------------------------- # Tests -my $tests = 28; -plan tests => 1 + $tests; +plan tests => 28; #---------------------------------------------------------------------------- # figure out if the test can actually run -note('Testing existence'); -my $loaded = use_ok('WebGUI::Shop::PayDriver::ITransact'); - my $e; -my $ship = WebGUI::Shop::Ship->new($session); -my $cart = WebGUI::Shop::Cart->newBySession($session); -my $shipper = $ship->getShipper('defaultfreeshipping000'); -my $address = $cart->getAddressBook->addAddress( { firstName => 'Ellis Boyd', lastName => 'Redding'} ); -$cart->update({ - shippingAddressId => $address->getId, - shipperId => $shipper->getId, -}); -my $transaction; - my $versionTag = WebGUI::VersionTag->getWorking($session); my $home = WebGUI::Asset->getDefault($session); @@ -82,14 +69,22 @@ my $foreignHammer = $rockHammer->setCollateral('variantsJSON', 'variantId', 'new $versionTag->commit; -WebGUI::Test->tagsToRollback($versionTag); +WebGUI::Test->addToCleanup($versionTag); +$rockHammer = $rockHammer->cloneFromDb; + +my $ship = WebGUI::Shop::Ship->new($session); +my $cart = WebGUI::Shop::Cart->newBySession($session); +WebGUI::Test->addToCleanup($cart); +my $shipper = $ship->getShipper('defaultfreeshipping000'); +my $address = $cart->getAddressBook->addAddress( { firstName => 'Ellis Boyd', lastName => 'Redding'} ); +$cart->update({ + shippingAddressId => $address->getId, + shipperId => $shipper->getId, +}); + my $hammerItem = $rockHammer->addToCart($rockHammer->getCollateral('variantsJSON', 'variantId', $smallHammer)); -SKIP: { - -skip 'Unable to load module WebGUI::Shop::PayDriver::ITransact', $tests unless $loaded; - ####################################################################### # # definition @@ -272,11 +267,12 @@ $driver->{_billingAddress} = { }; -$transaction = WebGUI::Shop::Transaction->create($session, { +my $transaction = WebGUI::Shop::Transaction->create($session, { paymentMethod => $driver, cart => $cart, isRecurring => $cart->requiresRecurringPayment, }); +WebGUI::Test->addToCleanup($transaction); my $xml = $driver->_generatePaymentRequestXML($transaction); @@ -292,11 +288,14 @@ TODO: { ####################################################################### SKIP: { - skip "Skipping XML requests to ITransact due to lack of userId and password", 2 unless $hasTestAccount; - my $response = eval { $driver->doXmlRequest($xml) }; + skip "Skipping XML requests to ITransact due to lack of real userId and password", 2 unless $hasTestAccount; note 'doXmlrequest'; - isa_ok($response, 'HTTP::Response', 'returns a HTTP::Response object'); - ok( $response->is_success, '... was successful'); + my $response = eval { $driver->doXmlRequest($xml) }; + my $ok_response = isa_ok($response, 'HTTP::Response', 'returns a HTTP::Response object'); + SKIP: { + skip "Skipping response check since we did not get a response", 1 unless $ok_response; + ok( $response->is_success, '... was successful'); + } } my $hammer2 = $rockHammer->addToCart($rockHammer->getCollateral('variantsJSON', 'variantId', $foreignHammer)); @@ -313,7 +312,6 @@ SKIP: { my $response = eval { $driver->doXmlRequest($xml) }; isa_ok($response, 'HTTP::Response', 'returns a HTTP::Response object'); ok( $response->is_success, '... was successful'); - note $response->content; } ####################################################################### @@ -332,13 +330,4 @@ is ($count, 0, 'delete deleted the object'); undef $driver; -#---------------------------------------------------------------------------- -# Cleanup - -} - -END: { - $cart->delete; - $transaction->delete if defined $transaction; -} #vim:ft=perl From 51827b9c27a28507c691fdc1b225a59e44f5c98c Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 23 May 2010 15:36:38 -0700 Subject: [PATCH 20/22] Fix the UPS test. --- t/Shop/ShipDriver/UPS.t | 3 +++ 1 file changed, 3 insertions(+) diff --git a/t/Shop/ShipDriver/UPS.t b/t/Shop/ShipDriver/UPS.t index 9a04dbfab..5312db984 100644 --- a/t/Shop/ShipDriver/UPS.t +++ b/t/Shop/ShipDriver/UPS.t @@ -110,6 +110,9 @@ my $blueFeather = $feather->setCollateral('variantsJSON', 'variantId', 'new', $versionTag->commit; addToCleanup($versionTag); +foreach my $asset($rockHammer, $bible, $feather) { + $asset = $asset->cloneFromDb; +} ####################################################################### # From 9a2b3bfd19c7543cf9407263c3f60918c84ad25c Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 23 May 2010 15:39:42 -0700 Subject: [PATCH 21/22] Update another test. --- t/Shop/ShipDriver/USPS.t | 3 +++ 1 file changed, 3 insertions(+) diff --git a/t/Shop/ShipDriver/USPS.t b/t/Shop/ShipDriver/USPS.t index 049c75b2b..6305737d7 100644 --- a/t/Shop/ShipDriver/USPS.t +++ b/t/Shop/ShipDriver/USPS.t @@ -109,6 +109,9 @@ my $gospels = $bible->setCollateral('variantsJSON', 'variantId', 'new', $versionTag->commit; addToCleanup($versionTag); +foreach my $asset ($bible, $rockHammer) { + $asset = $asset->cloneFromDb; +} ####################################################################### # From a95ebdf5de22fde5bb3f07cc7db6896c40bec4e0 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 23 May 2010 15:54:03 -0700 Subject: [PATCH 22/22] Fix these tests. They no longer die. --- t/Shop/ShipDriver/USPSInternational.t | 3 + t/Shop/TaxDriver/Generic.t | 1065 ++++++++++++------------- 2 files changed, 520 insertions(+), 548 deletions(-) diff --git a/t/Shop/ShipDriver/USPSInternational.t b/t/Shop/ShipDriver/USPSInternational.t index b2d3b07c1..e297de2b2 100644 --- a/t/Shop/ShipDriver/USPSInternational.t +++ b/t/Shop/ShipDriver/USPSInternational.t @@ -109,6 +109,9 @@ my $singlePage = $bible->setCollateral('variantsJSON', 'variantId', 'new', $versionTag->commit; addToCleanup($versionTag); +foreach my $asset ($rockHammer, $bible) { + $asset = $asset->cloneFromDb; +} ####################################################################### # diff --git a/t/Shop/TaxDriver/Generic.t b/t/Shop/TaxDriver/Generic.t index 8747219aa..2aec479c6 100644 --- a/t/Shop/TaxDriver/Generic.t +++ b/t/Shop/TaxDriver/Generic.t @@ -26,6 +26,7 @@ use WebGUI::Session; use WebGUI::Text; use WebGUI::Shop::Cart; use WebGUI::Shop::AddressBook; +use WebGUI::Shop::TaxDriver::Generic; #---------------------------------------------------------------------------- # Init @@ -36,620 +37,600 @@ my $session = WebGUI::Test->session; my $addExceptions = getAddExceptions($session); -my $tests = 78 + 2*scalar(@{$addExceptions}); -plan tests => 1 + $tests; +plan tests => 78 + + 2*scalar(@{$addExceptions}); #---------------------------------------------------------------------------- # put your tests here -my $loaded = use_ok('WebGUI::Shop::TaxDriver::Generic'); my $storage; my ($taxableDonation, $taxFreeDonation); -SKIP: { +####################################################################### +# +# new +# +####################################################################### - skip 'Unable to load module WebGUI::Shop::TaxDriver::Generic', $tests unless $loaded; +my $taxer = WebGUI::Shop::TaxDriver::Generic->new($session); - ####################################################################### - # - # new - # - ####################################################################### +isa_ok($taxer, 'WebGUI::Shop::TaxDriver::Generic'); - my $taxer = WebGUI::Shop::TaxDriver::Generic->new($session); +isa_ok($taxer->session, 'WebGUI::Session', 'session method returns a session object'); - isa_ok($taxer, 'WebGUI::Shop::TaxDriver::Generic'); +is($session->getId, $taxer->session->getId, 'session method returns OUR session object'); - isa_ok($taxer->session, 'WebGUI::Session', 'session method returns a session object'); +####################################################################### +# +# getItems +# +####################################################################### - is($session->getId, $taxer->session->getId, 'session method returns OUR session object'); +my $taxIterator = $taxer->getItems; - ####################################################################### - # - # getItems - # - ####################################################################### +isa_ok($taxIterator, 'WebGUI::SQL::ResultSet'); - my $taxIterator = $taxer->getItems; +is($taxIterator->rows, 0, 'WebGUI ships with no predefined tax data'); - isa_ok($taxIterator, 'WebGUI::SQL::ResultSet'); +####################################################################### +# +# add +# +####################################################################### - is($taxIterator->rows, 0, 'WebGUI ships with no predefined tax data'); +my $e; - ####################################################################### - # - # add - # - ####################################################################### +eval{$taxer->add()}; - my $e; - - eval{$taxer->add()}; +$e = Exception::Class->caught(); +isa_ok($e, 'WebGUI::Error::InvalidParam', 'add: correct type of exception thrown for missing hashref'); +is($e->error, 'Must pass in a hashref of params', 'add: correct message for a missing hashref'); +foreach my $inputSet ( @{ $addExceptions } ){ + eval{$taxer->add($inputSet->{args})}; $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidParam', 'add: correct type of exception thrown for missing hashref'); - is($e->error, 'Must pass in a hashref of params', 'add: correct message for a missing hashref'); - - foreach my $inputSet ( @{ $addExceptions } ){ - eval{$taxer->add($inputSet->{args})}; - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidParam', 'add: '.$inputSet->{comment}); - cmp_deeply( - $e, - methods( - error => $inputSet->{error}, - param => $inputSet->{param}, - ), - 'add: '.$inputSet->{comment}, - ); - } - - my $taxData = { - country => 'USA', - state => 'OR', - taxRate => '0', - }; - - my $oregonTaxId = $taxer->add($taxData); - - ok($session->id->valid($oregonTaxId), 'add method returns a valid GUID'); - - $taxIterator = $taxer->getItems; - is($taxIterator->rows, 1, 'add added only 1 row to the tax table'); - - my $addedData = $taxIterator->hashRef; - $taxData->{taxId} = $oregonTaxId; - $taxData->{city} = undef; - $taxData->{code} = undef; - - cmp_deeply($addedData, $taxData, 'add put the right data into the database for Oregon'); - - $taxData = { - country => 'USA', - state => 'Wisconsin', - city => 'Madcity', - code => '53702', - taxRate => '5', - }; - - my $wisconsinTaxId = $taxer->add($taxData); - - $taxIterator = $taxer->getItems; - is($taxIterator->rows, 2, 'add added another row to the tax table'); - - $taxData = { - country => 'USA', - state => 'Oregon', - taxRate => '0.1', - }; - - my $dupId = $taxer->add($taxData); - - $taxIterator = $taxer->getItems; - is($taxIterator->rows, 3, 'add permits adding duplicate information.'); - - ##Madison zip codes: - ##53701-53709 - ##city rate: 0.5% - ##Wisconsin rate 5.0% - - ####################################################################### - # - # getAllItems - # - ####################################################################### - - my $expectedTaxData = [ - { - country => 'USA', - state => 'OR', - city => undef, - code => undef, - taxRate => 0, - }, - { - country => 'USA', - state => 'Wisconsin', - city => 'Madcity', - code => '53702', - taxRate => 5, - }, - { - country => 'USA', - state => 'Oregon', - city => undef, - code => undef, - taxRate => 0.1, - }, - ]; - - cmp_bag( - $taxer->getAllItems, - $expectedTaxData, - 'getAllItems returns the whole set of tax data', - ); - - ####################################################################### - # - # delete - # - ####################################################################### - - eval{$taxer->delete()}; - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidParam', 'delete: error handling for missing hashref'); - is($e->error, 'Must pass in a hashref of params', 'delete: error message for missing hashref'); - - eval{$taxer->delete({})}; - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidParam', 'delete: error handling for missing key in hashref'); - is($e->error, 'Hash ref must contain a taxId key with a defined value', 'delete: error message for missing key in hashref'); - - eval{$taxer->delete({ taxId => undef })}; - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidParam', 'delete: error handling for an undefined taxId value'); - is($e->error, 'Hash ref must contain a taxId key with a defined value', 'delete: error message for an undefined taxId value'); - - $taxer->delete({ taxId => $dupId }); - $taxIterator = $taxer->getItems; - is($taxIterator->rows, 2, 'One row was deleted from the tax table, even though another row has duplicate information'); - - $taxer->delete({ taxId => $oregonTaxId }); - $taxIterator = $taxer->getItems; - is($taxIterator->rows, 1, 'Another row was deleted from the tax table'); - - $taxer->delete({ taxId => $session->id->generate }); - - $taxIterator = $taxer->getItems; - is($taxIterator->rows, 1, 'No rows were deleted from the table since the requested id does not exist'); - is($taxIterator->hashRef->{taxId}, $wisconsinTaxId, 'The correct tax information was deleted'); - - ######################################################################## - ## - ## exportTaxData - ## - ######################################################################## - - $storage = $taxer->exportTaxData(); - isa_ok($storage, 'WebGUI::Storage', 'exportTaxData returns a WebGUI::Storage object'); - is(substr($storage->getPathFrag, 0, 5), 'temp/', 'The storage object is in the temporary area'); - ok(-e $storage->getPath('siteTaxData.csv'), 'siteTaxData.csv file exists in the storage object'); - cmp_ok($storage->getFileSize('siteTaxData.csv'), '!=', 0, 'CSV file is not empty'); - my @fileLines = split /\n+/, $storage->getFileContentsAsScalar('siteTaxData.csv'); - #my @fileLines = (); - my @header = WebGUI::Text::splitCSV($fileLines[0]); - my @expectedHeader = qw/country state city code taxRate/; - cmp_deeply(\@header, \@expectedHeader, 'exportTaxData: header line is correct'); - my @row1 = WebGUI::Text::splitCSV($fileLines[1]); - my $wiData = $taxer->getItems->hashRef; - ##Need to ignore the taxId from the database - cmp_bag([ @{ $wiData }{ @expectedHeader } ], \@row1, 'exportTaxData: first line of data is correct'); - - my $newTaxId = $taxer->add({ - country => 'USA|U.S.A.', - state => 'washington|WA', - taxRate => '7', - code => '', - city => '', - }); - $taxer->delete({taxId => $wisconsinTaxId}); - $storage = $taxer->exportTaxData(); - @fileLines = split /\n+/, $storage->getFileContentsAsScalar('siteTaxData.csv'); - my @row1 = WebGUI::Text::splitCSV($fileLines[1]); - my $wiData = $taxer->getItems->hashRef; - ##Need to ignore the taxId from the database - cmp_bag([ @{ $wiData }{ @expectedHeader } ], \@row1, 'exportTaxData: first line of data is correct'); - - $taxer->delete({taxId => $newTaxId}); - - ####################################################################### - # - # import - # - ####################################################################### - - eval { $taxer->importTaxData(); }; - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidParam', 'importTaxData: error handling for an undefined taxId value'); - is($e->error, 'Must provide the path to a file', 'importTaxData: error handling for an undefined taxId value'); - - eval { $taxer->importTaxData('/path/to/nowhere'); }; - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidFile', 'importTaxData: error handling for file that does not exist in the filesystem'); - is($e->error, 'File could not be found', 'importTaxData: error handling for file that does not exist in the filesystem'); + isa_ok($e, 'WebGUI::Error::InvalidParam', 'add: '.$inputSet->{comment}); cmp_deeply( $e, methods( - brokenFile => '/path/to/nowhere', + error => $inputSet->{error}, + param => $inputSet->{param}, ), - 'importTaxData: error handling for file that does not exist in the filesystem', + 'add: '.$inputSet->{comment}, ); +} - my $taxFile = WebGUI::Test->getTestCollateralPath('taxTables/goodTaxTable.csv'); +my $taxData = { + country => 'USA', + state => 'OR', + taxRate => '0', +}; - SKIP: { - skip 'Root will cause this test to fail since it does not obey file permissions', 3 - if $< == 0; +my $oregonTaxId = $taxer->add($taxData); - my $originalChmod = (stat $taxFile)[2]; - chmod oct(0000), $taxFile; +ok($session->id->valid($oregonTaxId), 'add method returns a valid GUID'); - eval { $taxer->importTaxData($taxFile); }; - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidFile', 'importTaxData: error handling for file that cannot be read'); - is($e->error, 'File is not readable', 'importTaxData: error handling for file that that cannot be read'); - cmp_deeply( - $e, - methods( - brokenFile => $taxFile, - ), - 'importTaxData: error handling for file that that cannot be read', - ); +$taxIterator = $taxer->getItems; +is($taxIterator->rows, 1, 'add added only 1 row to the tax table'); - chmod $originalChmod, $taxFile; +my $addedData = $taxIterator->hashRef; +$taxData->{taxId} = $oregonTaxId; +$taxData->{city} = undef; +$taxData->{code} = undef; - } +cmp_deeply($addedData, $taxData, 'add put the right data into the database for Oregon'); - my $expectedTaxData = [ - { - country => 'USA', - state => '', - city => '', - code => '', - taxRate => 0, - }, - { - country => 'USA', - state => 'Wisconsin', - city => '', - code => '', - taxRate => 5, - }, - { - country => 'USA', - state => 'Wisconsin', - city => 'Madison', - code => '53701', - taxRate => 0.5, - }, - ]; +$taxData = { + country => 'USA', + state => 'Wisconsin', + city => 'Madcity', + code => '53702', + taxRate => '5', +}; - ok( - $taxer->importTaxData( - $taxFile - ), - 'Good tax data inserted', - ); +my $wisconsinTaxId = $taxer->add($taxData); - $taxIterator = $taxer->getItems; - is($taxIterator->rows, 3, 'import: Old data deleted, new data imported'); - cmp_bag( - $taxer->getAllItems, - $expectedTaxData, - 'Correct data inserted.', - ); +$taxIterator = $taxer->getItems; +is($taxIterator->rows, 2, 'add added another row to the tax table'); - ok( - $taxer->importTaxData( - WebGUI::Test->getTestCollateralPath('taxTables/orderedTaxTable.csv') - ), - 'Reordered tax data inserted', - ); +$taxData = { + country => 'USA', + state => 'Oregon', + taxRate => '0.1', +}; - $taxIterator = $taxer->getItems; - is($taxIterator->rows, 3, 'import: Old data deleted, new data imported again'); - cmp_bag( - $taxer->getAllItems, - $expectedTaxData, - 'Correct data inserted, with CSV in different columnar order.', - ); +my $dupId = $taxer->add($taxData); - ok( - $taxer->importTaxData( - WebGUI::Test->getTestCollateralPath('taxTables/commentedTaxTable.csv') - ), - 'Commented tax data inserted', - ); +$taxIterator = $taxer->getItems; +is($taxIterator->rows, 3, 'add permits adding duplicate information.'); - $taxIterator = $taxer->getItems; - is($taxIterator->rows, 3, 'import: Old data deleted, new data imported the third time'); - cmp_bag( - $taxer->getAllItems, - $expectedTaxData, - 'Correct data inserted, with comments in the CSV file', - ); +##Madison zip codes: +##53701-53709 +##city rate: 0.5% +##Wisconsin rate 5.0% - ok( - ! $taxer->importTaxData( - WebGUI::Test->getTestCollateralPath('taxTables/emptyTaxTable.csv') - ), - 'Empty tax data not inserted', - ); +####################################################################### +# +# getAllItems +# +####################################################################### - $taxIterator = $taxer->getItems; - is($taxIterator->rows, 3, 'import: Old data still exists and was not deleted'); - - my $failure; - eval { - $failure = $taxer->importTaxData( - WebGUI::Test->getTestCollateralPath('taxTables/badTaxTable.csv') - ); - }; - ok (!$failure, 'Tax data not imported'); - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidFile', 'importTaxData: a file with an error on 1 line'); - cmp_deeply( - $e, - methods( - error => 'Error found in the CSV file', - brokenFile => WebGUI::Test->getTestCollateralPath('taxTables/badTaxTable.csv'), - brokenLine => 1, - ), - 'importTaxData: error handling for file with errors in the CSV data', - ); - - eval { - $failure = $taxer->importTaxData( - WebGUI::Test->getTestCollateralPath('taxTables/missingHeaders.csv') - ); - }; - ok (!$failure, 'Tax data not imported when headers are missing'); - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidFile', 'importTaxData: a file with a missing header column'); - cmp_deeply( - $e, - methods( - error => 'Bad header found in the CSV file', - brokenFile => WebGUI::Test->getTestCollateralPath('taxTables/missingHeaders.csv'), - ), - 'importTaxData: error handling for a file with a missing header', - ); - - eval { - $failure = $taxer->importTaxData( - WebGUI::Test->getTestCollateralPath('taxTables/badHeaders.csv') - ); - }; - ok (!$failure, 'Tax data not imported when headers are wrong'); - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidFile', 'importTaxData: a file with a bad header column'); - cmp_deeply( - $e, - methods( - error => 'Bad header found in the CSV file', - brokenFile => WebGUI::Test->getTestCollateralPath('taxTables/badHeaders.csv'), - ), - 'importTaxData: error handling for a file with a bad header', - ); - - ok( - $taxer->importTaxData( - WebGUI::Test->getTestCollateralPath('taxTables/alternations.csv') - ), - 'Tax data with alternations inserted', - ); - - my $altData = $taxer->getItems->hashRef; ##Just 1 row - cmp_deeply( - $altData, +my $expectedTaxData = [ { - taxId => ignore, - country => q{U.S.A.,USA}, - state => q{WI,Wisconsin}, - city => q{Madison}, - code => 53701, + country => 'USA', + state => 'OR', + city => undef, + code => undef, + taxRate => 0, + }, + { + country => 'USA', + state => 'Wisconsin', + city => 'Madcity', + code => '53702', + taxRate => 5, + }, + { + country => 'USA', + state => 'Oregon', + city => undef, + code => undef, + taxRate => 0.1, + }, +]; + +cmp_bag( + $taxer->getAllItems, + $expectedTaxData, + 'getAllItems returns the whole set of tax data', +); + +####################################################################### +# +# delete +# +####################################################################### + +eval{$taxer->delete()}; +$e = Exception::Class->caught(); +isa_ok($e, 'WebGUI::Error::InvalidParam', 'delete: error handling for missing hashref'); +is($e->error, 'Must pass in a hashref of params', 'delete: error message for missing hashref'); + +eval{$taxer->delete({})}; +$e = Exception::Class->caught(); +isa_ok($e, 'WebGUI::Error::InvalidParam', 'delete: error handling for missing key in hashref'); +is($e->error, 'Hash ref must contain a taxId key with a defined value', 'delete: error message for missing key in hashref'); + +eval{$taxer->delete({ taxId => undef })}; +$e = Exception::Class->caught(); +isa_ok($e, 'WebGUI::Error::InvalidParam', 'delete: error handling for an undefined taxId value'); +is($e->error, 'Hash ref must contain a taxId key with a defined value', 'delete: error message for an undefined taxId value'); + +$taxer->delete({ taxId => $dupId }); +$taxIterator = $taxer->getItems; +is($taxIterator->rows, 2, 'One row was deleted from the tax table, even though another row has duplicate information'); + +$taxer->delete({ taxId => $oregonTaxId }); +$taxIterator = $taxer->getItems; +is($taxIterator->rows, 1, 'Another row was deleted from the tax table'); + +$taxer->delete({ taxId => $session->id->generate }); + +$taxIterator = $taxer->getItems; +is($taxIterator->rows, 1, 'No rows were deleted from the table since the requested id does not exist'); +is($taxIterator->hashRef->{taxId}, $wisconsinTaxId, 'The correct tax information was deleted'); + +######################################################################## +## +## exportTaxData +## +######################################################################## + +my $storage = $taxer->exportTaxData(); +WebGUI::Test->addToCleanup($storage); +isa_ok($storage, 'WebGUI::Storage', 'exportTaxData returns a WebGUI::Storage object'); +is(substr($storage->getPathFrag, 0, 5), 'temp/', 'The storage object is in the temporary area'); +ok(-e $storage->getPath('siteTaxData.csv'), 'siteTaxData.csv file exists in the storage object'); +cmp_ok($storage->getFileSize('siteTaxData.csv'), '!=', 0, 'CSV file is not empty'); +my @fileLines = split /\n+/, $storage->getFileContentsAsScalar('siteTaxData.csv'); +#my @fileLines = (); +my @header = WebGUI::Text::splitCSV($fileLines[0]); +my @expectedHeader = qw/country state city code taxRate/; +cmp_deeply(\@header, \@expectedHeader, 'exportTaxData: header line is correct'); +my @row1 = WebGUI::Text::splitCSV($fileLines[1]); +my $wiData = $taxer->getItems->hashRef; +##Need to ignore the taxId from the database +cmp_bag([ @{ $wiData }{ @expectedHeader } ], \@row1, 'exportTaxData: first line of data is correct'); + +my $newTaxId = $taxer->add({ + country => 'USA|U.S.A.', + state => 'washington|WA', + taxRate => '7', + code => '', + city => '', +}); +$taxer->delete({taxId => $wisconsinTaxId}); +$storage = $taxer->exportTaxData(); +@fileLines = split /\n+/, $storage->getFileContentsAsScalar('siteTaxData.csv'); +my @row1 = WebGUI::Text::splitCSV($fileLines[1]); +my $wiData = $taxer->getItems->hashRef; +##Need to ignore the taxId from the database +cmp_bag([ @{ $wiData }{ @expectedHeader } ], \@row1, 'exportTaxData: first line of data is correct'); + +$taxer->delete({taxId => $newTaxId}); + +####################################################################### +# +# import +# +####################################################################### + +eval { $taxer->importTaxData(); }; +$e = Exception::Class->caught(); +isa_ok($e, 'WebGUI::Error::InvalidParam', 'importTaxData: error handling for an undefined taxId value'); +is($e->error, 'Must provide the path to a file', 'importTaxData: error handling for an undefined taxId value'); + +eval { $taxer->importTaxData('/path/to/nowhere'); }; +$e = Exception::Class->caught(); +isa_ok($e, 'WebGUI::Error::InvalidFile', 'importTaxData: error handling for file that does not exist in the filesystem'); +is($e->error, 'File could not be found', 'importTaxData: error handling for file that does not exist in the filesystem'); +cmp_deeply( + $e, + methods( + brokenFile => '/path/to/nowhere', + ), + 'importTaxData: error handling for file that does not exist in the filesystem', +); + +my $taxFile = WebGUI::Test->getTestCollateralPath('taxTables/goodTaxTable.csv'); + +SKIP: { + skip 'Root will cause this test to fail since it does not obey file permissions', 3 + if $< == 0; + + my $originalChmod = (stat $taxFile)[2]; + chmod oct(0000), $taxFile; + + eval { $taxer->importTaxData($taxFile); }; + $e = Exception::Class->caught(); + isa_ok($e, 'WebGUI::Error::InvalidFile', 'importTaxData: error handling for file that cannot be read'); + is($e->error, 'File is not readable', 'importTaxData: error handling for file that that cannot be read'); + cmp_deeply( + $e, + methods( + brokenFile => $taxFile, + ), + 'importTaxData: error handling for file that that cannot be read', + ); + + chmod $originalChmod, $taxFile; + +} + +my $expectedTaxData = [ + { + country => 'USA', + state => '', + city => '', + code => '', + taxRate => 0, + }, + { + country => 'USA', + state => 'Wisconsin', + city => '', + code => '', + taxRate => 5, + }, + { + country => 'USA', + state => 'Wisconsin', + city => 'Madison', + code => '53701', taxRate => 0.5, }, - 'import: Data correctly loaded with alternations' - ); +]; - ####################################################################### - # - # getTaxRates - # - ####################################################################### - - ##Set up the tax information +ok( $taxer->importTaxData( - WebGUI::Test->getTestCollateralPath('taxTables/largeTaxTable.csv') + $taxFile ), - my $book = WebGUI::Shop::AddressBook->create($session); - my $taxingAddress = $book->addAddress({ - label => 'taxing', - city => 'Madison', - state => 'WI', - code => '53701', - country => 'USA', - }); - my $taxFreeAddress = $book->addAddress({ - label => 'no tax', - city => 'Portland', - state => 'OR', - code => '97123', - country => 'USA', - }); - my $alternateAddress = $book->addAddress({ - label => 'using alternations', - city => 'Los Angeles', - state => 'CalifornIA', - code => '92801', - country => 'USA', - }); + 'Good tax data inserted', +); - eval { $taxer->getTaxRates(); }; - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidObject', 'calculate: error handling for not sending a cart'); - cmp_deeply( - $e, - methods( - error => 'Need an address.', - got => '', - expected => 'WebGUI::Shop::Address', - ), - 'importTaxData: error handling for file that does not exist in the filesystem', +$taxIterator = $taxer->getItems; +is($taxIterator->rows, 3, 'import: Old data deleted, new data imported'); +cmp_bag( + $taxer->getAllItems, + $expectedTaxData, + 'Correct data inserted.', +); + +ok( + $taxer->importTaxData( + WebGUI::Test->getTestCollateralPath('taxTables/orderedTaxTable.csv') + ), + 'Reordered tax data inserted', +); + +$taxIterator = $taxer->getItems; +is($taxIterator->rows, 3, 'import: Old data deleted, new data imported again'); +cmp_bag( + $taxer->getAllItems, + $expectedTaxData, + 'Correct data inserted, with CSV in different columnar order.', +); + +ok( + $taxer->importTaxData( + WebGUI::Test->getTestCollateralPath('taxTables/commentedTaxTable.csv') + ), + 'Commented tax data inserted', +); + +$taxIterator = $taxer->getItems; +is($taxIterator->rows, 3, 'import: Old data deleted, new data imported the third time'); +cmp_bag( + $taxer->getAllItems, + $expectedTaxData, + 'Correct data inserted, with comments in the CSV file', +); + +ok( + ! $taxer->importTaxData( + WebGUI::Test->getTestCollateralPath('taxTables/emptyTaxTable.csv') + ), + 'Empty tax data not inserted', +); + +$taxIterator = $taxer->getItems; +is($taxIterator->rows, 3, 'import: Old data still exists and was not deleted'); + +my $failure; +eval { + $failure = $taxer->importTaxData( + WebGUI::Test->getTestCollateralPath('taxTables/badTaxTable.csv') ); +}; +ok (!$failure, 'Tax data not imported'); +$e = Exception::Class->caught(); +isa_ok($e, 'WebGUI::Error::InvalidFile', 'importTaxData: a file with an error on 1 line'); +cmp_deeply( + $e, + methods( + error => 'Error found in the CSV file', + brokenFile => WebGUI::Test->getTestCollateralPath('taxTables/badTaxTable.csv'), + brokenLine => 1, + ), + 'importTaxData: error handling for file with errors in the CSV data', +); - cmp_deeply( - $taxer->getTaxRates($taxingAddress), - [0, 5, 0.5], - 'getTaxRates: return correct data for a state with tax data' +eval { + $failure = $taxer->importTaxData( + WebGUI::Test->getTestCollateralPath('taxTables/missingHeaders.csv') ); +}; +ok (!$failure, 'Tax data not imported when headers are missing'); +$e = Exception::Class->caught(); +isa_ok($e, 'WebGUI::Error::InvalidFile', 'importTaxData: a file with a missing header column'); +cmp_deeply( + $e, + methods( + error => 'Bad header found in the CSV file', + brokenFile => WebGUI::Test->getTestCollateralPath('taxTables/missingHeaders.csv'), + ), + 'importTaxData: error handling for a file with a missing header', +); - cmp_deeply( - $taxer->getTaxRates($taxFreeAddress), - [0,0], - 'getTaxRates: return correct data for a state with no tax data' +eval { + $failure = $taxer->importTaxData( + WebGUI::Test->getTestCollateralPath('taxTables/badHeaders.csv') ); +}; +ok (!$failure, 'Tax data not imported when headers are wrong'); +$e = Exception::Class->caught(); +isa_ok($e, 'WebGUI::Error::InvalidFile', 'importTaxData: a file with a bad header column'); +cmp_deeply( + $e, + methods( + error => 'Bad header found in the CSV file', + brokenFile => WebGUI::Test->getTestCollateralPath('taxTables/badHeaders.csv'), + ), + 'importTaxData: error handling for a file with a bad header', +); - cmp_deeply( - $taxer->getTaxRates($alternateAddress), - [0.0, 8.25], #Hits USA and Los Angeles, California using the alternate spelling of the state - 'getTaxRates: return correct data for a state when the address has alternations' - ); +ok( + $taxer->importTaxData( + WebGUI::Test->getTestCollateralPath('taxTables/alternations.csv') + ), + 'Tax data with alternations inserted', +); - ####################################################################### - # - # calculate - # - ####################################################################### +my $altData = $taxer->getItems->hashRef; ##Just 1 row +cmp_deeply( + $altData, + { + taxId => ignore, + country => q{U.S.A.,USA}, + state => q{WI,Wisconsin}, + city => q{Madison}, + code => 53701, + taxRate => 0.5, + }, + 'import: Data correctly loaded with alternations' +); - eval { $taxer->getTaxRate(); }; - $e = Exception::Class->caught(); - isa_ok($e, 'WebGUI::Error::InvalidParam', 'getTaxRate: error handling for not sending a sku'); - is($e->error, 'Must pass in a WebGUI::Asset::Sku object', 'getTaxRate: error handling for not sending a sku'); +####################################################################### +# +# getTaxRates +# +####################################################################### - ##Build a cart, add some Donation SKUs to it. Set one to be taxable. +##Set up the tax information +$taxer->importTaxData( + WebGUI::Test->getTestCollateralPath('taxTables/largeTaxTable.csv') +), +my $book = WebGUI::Shop::AddressBook->create($session); +my $taxingAddress = $book->addAddress({ + label => 'taxing', + city => 'Madison', + state => 'WI', + code => '53701', + country => 'USA', +}); +my $taxFreeAddress = $book->addAddress({ + label => 'no tax', + city => 'Portland', + state => 'OR', + code => '97123', + country => 'USA', +}); +my $alternateAddress = $book->addAddress({ + label => 'using alternations', + city => 'Los Angeles', + state => 'CalifornIA', + code => '92801', + country => 'USA', +}); - my $cart = WebGUI::Shop::Cart->newBySession($session); +eval { $taxer->getTaxRates(); }; +$e = Exception::Class->caught(); +isa_ok($e, 'WebGUI::Error::InvalidObject', 'calculate: error handling for not sending a cart'); +cmp_deeply( + $e, + methods( + error => 'Need an address.', + got => '', + expected => 'WebGUI::Shop::Address', + ), + 'importTaxData: error handling for file that does not exist in the filesystem', +); + +cmp_deeply( + $taxer->getTaxRates($taxingAddress), + [0, 5, 0.5], + 'getTaxRates: return correct data for a state with tax data' +); + +cmp_deeply( + $taxer->getTaxRates($taxFreeAddress), + [0,0], + 'getTaxRates: return correct data for a state with no tax data' +); + +cmp_deeply( + $taxer->getTaxRates($alternateAddress), + [0.0, 8.25], #Hits USA and Los Angeles, California using the alternate spelling of the state + 'getTaxRates: return correct data for a state when the address has alternations' +); + +####################################################################### +# +# calculate +# +####################################################################### + +eval { $taxer->getTaxRate(); }; +$e = Exception::Class->caught(); +isa_ok($e, 'WebGUI::Error::InvalidParam', 'getTaxRate: error handling for not sending a sku'); +is($e->error, 'Must pass in a WebGUI::Asset::Sku object', 'getTaxRate: error handling for not sending a sku'); + +##Build a cart, add some Donation SKUs to it. Set one to be taxable. + +my $cart = WebGUI::Shop::Cart->newBySession($session); +WebGUI::Test->addToCleanup($cart); # is($taxer->calculate($cart), 0, 'calculate returns 0 if there is no shippingAddressId in the cart'); # $cart->update({ shippingAddressId => $taxingAddress->getId}); - ##Set up the tax information - $taxer->importTaxData( - WebGUI::Test->getTestCollateralPath('taxTables/largeTaxTable.csv') - ), +##Set up the tax information +$taxer->importTaxData( + WebGUI::Test->getTestCollateralPath('taxTables/largeTaxTable.csv') +), - $taxableDonation = WebGUI::Asset->getRoot($session)->addChild({ - className => 'WebGUI::Asset::Sku::Donation', - title => 'Taxable donation', - defaultPrice => 100.00, - }); +my $taxableDonation = WebGUI::Asset->getRoot($session)->addChild({ + className => 'WebGUI::Asset::Sku::Donation', + title => 'Taxable donation', + defaultPrice => 100.00, +}); - is($taxer->getTaxRate($taxableDonation), 0, 'calculate returns 0 if there is no shippingAddressId in the cart'); +my $tag1 = WebGUI::VersionTag->getWorking($session); +$tag1->commit; +WebGUI::Test->addToCleanup($tag1); +$taxableDonation = $taxableDonation->cloneFromDb; +is($taxer->getTaxRate($taxableDonation), 0, 'calculate returns 0 if there is no shippingAddressId in the cart'); -# $cart->addItem($taxableDonation); +my $tax = $taxer->getTaxRate( $taxableDonation, $taxingAddress ); +is($tax, 5.5, 'calculate: simple tax calculation on 1 item in the cart'); -# foreach my $item (@{ $cart->getItems }) { -# $item->setQuantity(1); -# } +$cart->update({ shippingAddressId => $taxFreeAddress->getId}); +is($taxer->getTaxRate( $taxableDonation, $taxFreeAddress ), 0, 'calculate: simple tax calculation on 1 item in the cart, tax free location'); - my $tax = $taxer->getTaxRate( $taxableDonation, $taxingAddress ); - is($tax, 5.5, 'calculate: simple tax calculation on 1 item in the cart'); +my $taxFreeDonation = WebGUI::Asset->getRoot($session)->addChild({ + className => 'WebGUI::Asset::Sku::Donation', + title => 'Tax Free Donation', + defaultPrice => 100.00, +}); - $cart->update({ shippingAddressId => $taxFreeAddress->getId}); - is($taxer->getTaxRate( $taxableDonation, $taxFreeAddress ), 0, 'calculate: simple tax calculation on 1 item in the cart, tax free location'); +my $tag2 = WebGUI::VersionTag->getWorking($session); +$tag2->commit; +WebGUI::Test->addToCleanup($tag2); +$taxFreeDonation = $taxFreeDonation->cloneFromDb; -# foreach my $item (@{ $cart->getItems }) { -# $item->setQuantity(2); -# } +$taxFreeDonation->setTaxConfiguration( 'WebGUI::Shop::TaxDriver::Generic', { + overrideTaxRate => 1, + taxRateOverride => 0, +}); + +is($taxer->getTaxRate( $taxFreeDonation, $taxingAddress), 0, 'getTaxRate: tax rate override should override tax derived from address'); + +####################################################################### # -# $cart->update({ shippingAddressId => $taxingAddress->getId}); -# is($taxer->calculate($cart), 11, 'calculate: simple tax calculation on 1 item in the cart, qty 2'); - - $taxFreeDonation = WebGUI::Asset->getRoot($session)->addChild({ - className => 'WebGUI::Asset::Sku::Donation', - title => 'Tax Free Donation', - defaultPrice => 100.00, - }); - $taxFreeDonation->setTaxConfiguration( 'WebGUI::Shop::TaxDriver::Generic', { - overrideTaxRate => 1, - taxRateOverride => 0, - }); - -# $cart->addItem($taxFreeDonation); - -# foreach my $item (@{ $cart->getItems }) { -# $item->setQuantity(1); -# } - is($taxer->getTaxRate( $taxFreeDonation, $taxingAddress), 0, 'getTaxRate: tax rate override should override tax derived from address'); - -# my $remoteItem = $cart->addItem($taxableDonation); -# $remoteItem->update({shippingAddressId => $taxFreeAddress->getId}); +# www_getTaxesAsJson # -# foreach my $item (@{ $cart->getItems }) { -# $item->setQuantity(1); -# } -# is($taxer->calculate($cart), 5.5, 'calculate: simple tax calculation on 2 items in the cart, 1 without taxes, 1 shipped to a location with no taxes'); +####################################################################### - ####################################################################### - # - # www_getTaxesAsJson - # - ####################################################################### +$session->user({userId=>3}); +my $json = $taxer->www_getTaxesAsJson(); +ok($json, 'www_getTaxesAsJson returned something'); +is($session->http->getMimeType, 'application/json', 'MIME type set to application/json'); +my $jsonTax = JSON::from_json($json); +cmp_deeply( + $jsonTax, + { + sort => undef, + startIndex => 0, + totalRecords => 1778, + recordsReturned => 25, + dir => 'asc', + records => array_each({ + taxId=>ignore, + country => 'USA', + state=>ignore, + city=>ignore, + code=>ignore, + taxRate=>re('^\d+(\.\d+)?$') + }), + }, + 'Check major elements of tax JSON', +); - $session->user({userId=>3}); - my $json = $taxer->www_getTaxesAsJson(); - ok($json, 'www_getTaxesAsJson returned something'); - is($session->http->getMimeType, 'application/json', 'MIME type set to application/json'); - my $jsonTax = JSON::from_json($json); - cmp_deeply( - $jsonTax, - { - sort => undef, - startIndex => 0, - totalRecords => 1778, - recordsReturned => 25, - dir => 'asc', - records => array_each({ - taxId=>ignore, - country => 'USA', - state=>ignore, - city=>ignore, - code=>ignore, - taxRate=>re('^\d+(\.\d+)?$') - }), - }, - 'Check major elements of tax JSON', - ); - - TODO: { - local $TODO = 'More getTaxesAsJson tests'; - ok(0, 'test group privileges to this method'); - ok(0, 'test startIndex variable'); - ok(0, 'test results form variable'); - ok(0, 'test keywords'); - } - - $cart->delete; - $book->delete; - $taxableDonation->purge; - $taxFreeDonation->purge; +TODO: { + local $TODO = 'More getTaxesAsJson tests'; + ok(0, 'test group privileges to this method'); + ok(0, 'test startIndex variable'); + ok(0, 'test results form variable'); + ok(0, 'test keywords'); } +$cart->delete; +$book->delete; +$taxableDonation->purge; +$taxFreeDonation->purge; + sub getAddExceptions { my $session = shift; my $inputValidion = [ @@ -690,16 +671,4 @@ sub getAddExceptions { # Cleanup END { $session->db->write('delete from tax_generic_rates'); - $session->db->write('delete from cart'); - $session->db->write('delete from addressBook'); - $session->db->write('delete from address'); - $storage->delete; - - if (defined $taxableDonation and ref $taxableDonation eq 'WebGUI::Sku::Donation') { - $taxableDonation->purge; - } - - if (defined $taxFreeDonation and ref $taxFreeDonation eq 'WebGUI::Sku::Donation') { - $taxFreeDonation->purge; - } }