From 04ee8f0949d1e6eaa05f4b55e959ff0f379187c1 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 7 May 2010 18:34:55 -0700 Subject: [PATCH 001/101] Fix the Group tests. --- t/Group.t | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/t/Group.t b/t/Group.t index d1b43d765..0b549cc45 100644 --- a/t/Group.t +++ b/t/Group.t @@ -18,7 +18,6 @@ use WebGUI::Utility; use WebGUI::User; use WebGUI::Group; -use WebGUI::Cache; use Test::More; use Test::Deep; @@ -78,8 +77,7 @@ my @ipTests = ( plan tests => (151 + scalar(@scratchTests) + scalar(@ipTests)); # increment this value for each test you create my $session = WebGUI::Test->session; -my $testCache = WebGUI::Cache->new($session, 'myTestKey'); -$testCache->flush; +$session->cache->remove('myTestKey'); foreach my $gid ('new', '') { my $g = WebGUI::Group->new($session, $gid); @@ -437,7 +435,8 @@ cmp_bag($mobUsers, [map {$_->userId} @mob], 'verify SQL table built correctly'); is( $gY->databaseLinkId, 0, "Group Y's databaseLinkId is set to WebGUI"); $gY->dbQuery(q!select userId from myUserTable!); is( $session->stow->get('isInGroup'), undef, 'setting dbQuery clears cached isInGroup'); -WebGUI::Cache->new($session, $gZ->getId)->delete(); ##Delete cached key for testing +#WebGUI::Cache->new($session, $gZ->getId)->delete(); ##Delete cached key for testing +$session->cache->remove($gZ->getId); my @mobIds = map { $_->userId } @mob; @@ -684,5 +683,5 @@ ok(! WebGUI::Group->vitalGroup('27'), '... 27 is not vital'); END { $session->db->dbh->do('DROP TABLE IF EXISTS myUserTable'); - $testCache->flush; + $session->cache->remove('myTestKey'); } From 0bef2b2839e176b599b4dc14614f1275333f77ef Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 14:30:47 -0700 Subject: [PATCH 002/101] Change the core to use newById instead of new. --- lib/WebGUI/Macro/PickLanguage.pm | 2 +- lib/WebGUI/Shop/Pay.pm | 2 +- lib/WebGUI/Shop/Transaction.pm | 2 +- lib/WebGUI/Workflow/Activity/ExtendCalendarRecurrences.pm | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/WebGUI/Macro/PickLanguage.pm b/lib/WebGUI/Macro/PickLanguage.pm index a1af2a40b..750867efd 100644 --- a/lib/WebGUI/Macro/PickLanguage.pm +++ b/lib/WebGUI/Macro/PickLanguage.pm @@ -44,7 +44,7 @@ This macro takes a templateId to show the links sub process { my $session = shift; my $templateId = shift || "_aE16Rr1-bXBf8SIaLZjCg"; - my $template = WebGUI::Asset::Template->new($session, $templateId); + my $template = WebGUI::Asset::Template->newById($session, $templateId); return "Could not instanciate template with id [$templateId]" unless $template; my $i18n = WebGUI::International->new($session); my $languages = $i18n->getLanguages(); diff --git a/lib/WebGUI/Shop/Pay.pm b/lib/WebGUI/Shop/Pay.pm index 8d1c91a52..bdb54fad0 100644 --- a/lib/WebGUI/Shop/Pay.pm +++ b/lib/WebGUI/Shop/Pay.pm @@ -431,7 +431,7 @@ sub www_selectPaymentGateway { } $var->{ paymentGateways } = \@paymentGateways; $var->{ choose } = $i18n->get('choose payment gateway message'); - my $template = WebGUI::Asset::Template->new($session, $session->setting->get("selectGatewayTemplateId")); + my $template = WebGUI::Asset::Template->newById($session, $session->setting->get("selectGatewayTemplateId")); return $session->style->userStyle($template->process($var)); } diff --git a/lib/WebGUI/Shop/Transaction.pm b/lib/WebGUI/Shop/Transaction.pm index 7619dbc51..bc707daee 100644 --- a/lib/WebGUI/Shop/Transaction.pm +++ b/lib/WebGUI/Shop/Transaction.pm @@ -633,7 +633,7 @@ sub sendNotifications { my $var = $self->getTransactionVars; # render - my $template = WebGUI::Asset::Template->new( $session, $session->setting->get("shopReceiptEmailTemplateId") ); + my $template = WebGUI::Asset::Template->newById( $session, $session->setting->get("shopReceiptEmailTemplateId") ); my $inbox = WebGUI::Inbox->new($session); my $receipt = $template->process( $var ); WebGUI::Macro::process($session, \$receipt); diff --git a/lib/WebGUI/Workflow/Activity/ExtendCalendarRecurrences.pm b/lib/WebGUI/Workflow/Activity/ExtendCalendarRecurrences.pm index 5f85b184e..56ee5a27e 100644 --- a/lib/WebGUI/Workflow/Activity/ExtendCalendarRecurrences.pm +++ b/lib/WebGUI/Workflow/Activity/ExtendCalendarRecurrences.pm @@ -164,7 +164,7 @@ exhausted the recurrence, false otherwise. sub processRecurrence { my ( $self, $recurId, $timeLimit ) = @_; my $eventId = $self->findLastEventId($recurId); - my $event = WebGUI::Asset::Event->new( $self->session, $eventId ); + my $event = WebGUI::Asset::Event->newById( $self->session, $eventId ); my $recur = $event->getRecurrence; my $start = $event->getDateTimeStart->truncate(to => 'day'); From 8272c2b087ed764ec383abe7da5c398398aa1935 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 14:51:20 -0700 Subject: [PATCH 003/101] Do not intstall a wrapper around new in Asset.pm --- t/lib/WebGUI/Test.pm | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/t/lib/WebGUI/Test.pm b/t/lib/WebGUI/Test.pm index 3ed762aa5..16fdc2c2a 100644 --- a/t/lib/WebGUI/Test.pm +++ b/t/lib/WebGUI/Test.pm @@ -240,15 +240,15 @@ sub _mockAssetInits { if $mockedNew; require WebGUI::Asset; my $original_new = \&WebGUI::Asset::new; - *WebGUI::Asset::new = sub { - my ($class, $session, $assetId, $className, $revisionDate) = @_; - if ($mockedAssetIds{$assetId}) { - return $mockedAssetIds{$assetId}; - } - goto $original_new; - }; - my $original_newByDynamicClass = \&WebGUI::Asset::newByDynamicClass; - *WebGUI::Asset::newByDynamicClass = sub { +# *WebGUI::Asset::new = sub { +# my ($class, $session, $assetId, $className, $revisionDate) = @_; +# if ($mockedAssetIds{$assetId}) { +# return $mockedAssetIds{$assetId}; +# } +# goto $original_new; +# }; + my $original_newByDynamicClass = \&WebGUI::Asset::newById; + *WebGUI::Asset::newById = sub { my ($class, $session, $assetId, $revisionDate) = @_; if ($mockedAssetIds{$assetId}) { return $mockedAssetIds{$assetId}; @@ -263,6 +263,14 @@ sub _mockAssetInits { } goto $original_newPending; }; + my $original_newByPropertyHashRef = \&WebGUI::Asset::newByPropertyHashRef; + *WebGUI::Asset::newByPropertyHashRef = sub { + my ($class, $session, $url, $revisionDate) = @_; + if ($url && $mockedAssetUrls{$url}) { + return $mockedAssetUrls{$url}; + } + goto $original_newByPropertyHashRef; + }; my $original_newByUrl = \&WebGUI::Asset::newByUrl; *WebGUI::Asset::newByUrl = sub { my ($class, $session, $url, $revisionDate) = @_; From c471cd145b1b61b10e244bdc9a99ad9d6fe4245c Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 14:59:30 -0700 Subject: [PATCH 004/101] Fix a test I broke. --- t/Shop/AddressBook.t | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/t/Shop/AddressBook.t b/t/Shop/AddressBook.t index b73838fd6..a234b0fce 100644 --- a/t/Shop/AddressBook.t +++ b/t/Shop/AddressBook.t @@ -23,6 +23,7 @@ use Exception::Class; use WebGUI::Test; # Must use this before any other WebGUI modules use WebGUI::Session; use WebGUI::Text; +use WebGUI::Shop::AddressBook; #---------------------------------------------------------------------------- # Init @@ -195,7 +196,7 @@ is($bookCount, 1, 'delete: one book deleted'); $bookClone->delete(); $bookCount = $session->db->quickScalar('select count(*) from addressBook'); -my $addrCount = $session->db->quickScalar('select count(*) from address'); +$addrCount = $session->db->quickScalar('select count(*) from address'); is($bookCount, 0, '... book deleted'); is($addrCount, 0, '... also deletes addresses in the book'); From 10d96d38167c9108ea5b28ff684eef733f632c7a Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 15:01:22 -0700 Subject: [PATCH 005/101] Update help for new operational code. --- t/Help/related.t | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/t/Help/related.t b/t/Help/related.t index 7ca1494e9..b3c31e2f4 100644 --- a/t/Help/related.t +++ b/t/Help/related.t @@ -28,14 +28,14 @@ my $numTests = 0; my $session = WebGUI::Test->session; -my @helpFileSet = WebGUI::Operation::Help::_getHelpFilesList($session); +my @helpFileSet = WebGUI::Pluggable::findAndLoad('WebGUI::Help'); my %helpTable; foreach my $helpSet (@helpFileSet) { - my $helpName = $helpSet->[1]; - my $help = WebGUI::Operation::Help::_load($session, $helpName); - $helpTable{ $helpName } = $help; + my ($namespace) = $helpSet =~ m{WebGUI::Help::(.+$)}; + my $help = WebGUI::Operation::Help::_load($session, $namespace); + $helpTable{ $namespace } = $help; } ##Scan #1, how many tests do we expect? From 2c80c501c6709d15f86afdbc7d3e6194121e0402 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 15:05:41 -0700 Subject: [PATCH 006/101] Test assets for valid methods before calling them. --- lib/WebGUI/Macro/FileUrl.pm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/WebGUI/Macro/FileUrl.pm b/lib/WebGUI/Macro/FileUrl.pm index b52fa238f..b9adc624b 100644 --- a/lib/WebGUI/Macro/FileUrl.pm +++ b/lib/WebGUI/Macro/FileUrl.pm @@ -48,11 +48,11 @@ sub process { if (Exception::Class->caught()) { return $i18n->get('invalid url'); } - my $storageId = $asset->storageId; + my $storageId = $asset->can('storageId') ? $asset->storageId : undef; if (not defined $storageId) { return $i18n->get('no storage'); } - my $filename = $asset->filename; + my $filename = $asset->can('filename') ? $asset->filename : undef; if (not defined $filename) { return $i18n->get('no filename'); } From ab6476012ab4235c3c55b10489988988e1f9c920 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 15:08:18 -0700 Subject: [PATCH 007/101] Add missing module use line to Group.pm --- lib/WebGUI/Group.pm | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/WebGUI/Group.pm b/lib/WebGUI/Group.pm index b1a35e7d7..4d0133e98 100644 --- a/lib/WebGUI/Group.pm +++ b/lib/WebGUI/Group.pm @@ -21,6 +21,7 @@ use WebGUI::Utility; use WebGUI::Pluggable; require WebGUI::Asset; use WebGUI::International; +use WebGUI::DatabaseLink; =head1 NAME From 4ecc8dce2a08bdef60c8a63fb3fdc55191b7895a Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 15:27:39 -0700 Subject: [PATCH 008/101] AssetLineage should throw exceptions. --- lib/WebGUI/AssetLineage.pm | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/WebGUI/AssetLineage.pm b/lib/WebGUI/AssetLineage.pm index 2fb1d0b16..95840cc12 100644 --- a/lib/WebGUI/AssetLineage.pm +++ b/lib/WebGUI/AssetLineage.pm @@ -829,8 +829,7 @@ sub newByLineage { unless ($id) { ($id) = $session->db->quickArray("select assetId from asset where lineage=?",[$lineage]); if (!$id) { - $session->errorHandler->error("Couldn't instantiate asset from lineage: ".$lineage. ": assetId missing"); - return undef; + WebGUI::Error::InvalidParam->throw(error => "Cannot find lineage date for assetId", param => $id); } $assetLineage->{$lineage}{id} = $id; $session->stow->set("assetLineage",$assetLineage); From a2feddc3b5254b7d5235cfa6cea59015db0b47cf Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 15:35:07 -0700 Subject: [PATCH 009/101] Exception handling. --- lib/WebGUI/Macro/PickLanguage.pm | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/WebGUI/Macro/PickLanguage.pm b/lib/WebGUI/Macro/PickLanguage.pm index 750867efd..a59aead4d 100644 --- a/lib/WebGUI/Macro/PickLanguage.pm +++ b/lib/WebGUI/Macro/PickLanguage.pm @@ -44,8 +44,10 @@ This macro takes a templateId to show the links sub process { my $session = shift; my $templateId = shift || "_aE16Rr1-bXBf8SIaLZjCg"; - my $template = WebGUI::Asset::Template->newById($session, $templateId); + my $template = eval { WebGUI::Asset::Template->newById($session, $templateId); }; + if (Exception::Class->caught()) { return "Could not instanciate template with id [$templateId]" unless $template; + } my $i18n = WebGUI::International->new($session); my $languages = $i18n->getLanguages(); my @lang_loop = (); From 97d5caab1786010cfd55de5f8eeadf14ef780e44 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 15:37:13 -0700 Subject: [PATCH 010/101] Exception handling for Thumbnail macro. --- lib/WebGUI/Macro/Thumbnail.pm | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/WebGUI/Macro/Thumbnail.pm b/lib/WebGUI/Macro/Thumbnail.pm index 3c67d7ba0..089ffbb40 100644 --- a/lib/WebGUI/Macro/Thumbnail.pm +++ b/lib/WebGUI/Macro/Thumbnail.pm @@ -32,13 +32,15 @@ Image Asset can be found with that URL, then undef will be returned. #------------------------------------------------------------------- sub process { - my $session = shift; - my $url = shift; - if (my $image = WebGUI::Asset::File::Image->newByUrl($session,$url)) { - return $image->getThumbnailUrl; - } else { - return undef; - } + my $session = shift; + my $url = shift; + my $image = eval { WebGUI::Asset::File::Image->newByUrl($session,$url) }; + if (Exception::Class->caught()) { + return undef; + } + else { + return $image->getThumbnailUrl; + } } From 8bbf758f531387876ebfce7cc22ec62f54857e5e Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 16:13:28 -0700 Subject: [PATCH 011/101] Update FlatRate test. --- t/Shop/ShipDriver/FlatRate.t | 63 ++++++++++++------------------------ 1 file changed, 20 insertions(+), 43 deletions(-) diff --git a/t/Shop/ShipDriver/FlatRate.t b/t/Shop/ShipDriver/FlatRate.t index 082a7eaef..d8202d48b 100644 --- a/t/Shop/ShipDriver/FlatRate.t +++ b/t/Shop/ShipDriver/FlatRate.t @@ -37,15 +37,7 @@ plan tests => 1 + $tests; #---------------------------------------------------------------------------- # put your tests here -my $loaded = use_ok('WebGUI::Shop::ShipDriver::FlatRate'); - -my $storage; -my ($driver, $cart, $car, $key); -my $versionTag; - -SKIP: { - -skip 'Unable to load module WebGUI::Shop::ShipDriver::FlatRate', $tests unless $loaded; +use_ok('WebGUI::Shop::ShipDriver::FlatRate'); ####################################################################### # @@ -142,11 +134,11 @@ my $options = { pricePerItem => 0.1, }; -$driver = WebGUI::Shop::ShipDriver::FlatRate->create($session, $options); +my $driver2 = WebGUI::Shop::ShipDriver::FlatRate->create($session, $options); -isa_ok($driver, 'WebGUI::Shop::ShipDriver::FlatRate'); +isa_ok($driver2, 'WebGUI::Shop::ShipDriver::FlatRate'); -isa_ok($driver, 'WebGUI::Shop::ShipDriver'); +isa_ok($driver2, 'WebGUI::Shop::ShipDriver'); ####################################################################### # @@ -162,7 +154,7 @@ is (WebGUI::Shop::ShipDriver::FlatRate->getName($session), 'Flat Rate', 'getName # ####################################################################### -my $form = $driver->getEditForm; +my $form = $driver2->getEditForm; isa_ok($form, 'WebGUI::HTMLForm', 'getEditForm returns an HTMLForm object'); @@ -252,13 +244,13 @@ cmp_deeply( # ####################################################################### -my $driverId = $driver->getId; -$driver->delete; +my $driverId = $driver2->getId; +$driver2->delete; my $count = $session->db->quickScalar('select count(*) from shipper where shipperId=?',[$driverId]); is($count, 0, 'delete deleted the object'); -undef $driver; +undef $driver2; ####################################################################### # @@ -266,11 +258,12 @@ undef $driver; # ####################################################################### -$car = WebGUI::Asset->getImportNode($session)->addChild({ +my $car = WebGUI::Asset->getImportNode($session)->addChild({ className => 'WebGUI::Asset::Sku::Product', title => 'Automobiles', isShippingRequired => 1, }); +WebGUI::Test->addToCleanup($car); my $crappyCar = $car->setCollateral('variantsJSON', 'variantId', 'new', { @@ -302,8 +295,10 @@ my $reallyNiceCar = $car->setCollateral('variantsJSON', 'variantId', 'new', } ); -$versionTag = WebGUI::VersionTag->getWorking($session); +my $versionTag = WebGUI::VersionTag->getWorking($session); $versionTag->commit; +WebGUI::Test->addToCleanup($versionTag); +$car = $car->cloneFromDb; $options = { label => 'flat rate, ship weight', @@ -314,9 +309,11 @@ $options = { pricePerItem => 10, }; -$driver = WebGUI::Shop::ShipDriver::FlatRate->create($session, $options); +my $driver = WebGUI::Shop::ShipDriver::FlatRate->create($session, $options); +WebGUI::Test->addToCleanup($driver); -$cart = WebGUI::Shop::Cart->newBySession($session); +my $cart = WebGUI::Shop::Cart->newBySession($session); +WebGUI::Test->addToCleanup($cart); $car->addToCart($car->getCollateral('variantsJSON', 'variantId', $crappyCar)); is($driver->calculate($cart), 1511, 'calculate by weight, perItem and flat fee work'); @@ -345,7 +342,7 @@ $driver->update({ pricePerItem => 0, }); -$key = WebGUI::Asset->getImportNode($session)->addChild({ +my $key = WebGUI::Asset->getImportNode($session)->addChild({ className => 'WebGUI::Asset::Sku::Product', title => 'Key', isShippingRequired => 1, @@ -372,6 +369,8 @@ my $bioKey = $key->setCollateral('variantsJSON', 'variantId', 'new', } ); +WebGUI::Test->addToCleanup($key); + my $boughtCar = $car->addToCart($car->getCollateral('variantsJSON', 'variantId', $reallyNiceCar)); my $firstKey = $key->addToCart($key->getCollateral('variantsJSON', 'variantId', $metalKey)); is($driver->calculate($cart), 2, 'shipsSeparately: returns two, one for ships separately, one for ships bundled'); @@ -388,25 +387,3 @@ is($driver->calculate($cart), 1, '... returns one, since all can be bundled toge $car->update({shipsSeparately => 1}); $key->update({shipsSeparately => 1}); is($driver->calculate($cart), 4, '... returns four, since all must be shipped separately now'); - -} - -#---------------------------------------------------------------------------- -# Cleanup -END { - if (defined $driver && ref $driver eq 'WebGUI::Shop::ShipDriver::FlatRate') { - $driver->delete; - } - if (defined $cart && ref $cart eq 'WebGUI::Shop::Cart') { - $cart->delete; - } - if (defined $car && (ref($car) eq 'WebGUI::Asset::Sku::Product')) { - $car->purge; - } - if (defined $key && (ref($key) eq 'WebGUI::Asset::Sku::Product')) { - $key->purge; - } - if (defined $versionTag) { - $versionTag->rollback; - } -} From 69a1b4e18025d6b710054b6cee863d92b4affcb9 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 17:25:27 -0700 Subject: [PATCH 012/101] Update test for new asset instanciators. --- t/Workflow/Activity/NotifyAboutLowStock.t | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/t/Workflow/Activity/NotifyAboutLowStock.t b/t/Workflow/Activity/NotifyAboutLowStock.t index 909a2caec..728533e16 100644 --- a/t/Workflow/Activity/NotifyAboutLowStock.t +++ b/t/Workflow/Activity/NotifyAboutLowStock.t @@ -41,6 +41,7 @@ my $posters = $import->addChild({ my $versionTag = WebGUI::VersionTag->getWorking($session); $versionTag->commit(); addToCleanup($versionTag); +$posters = $posters->cloneFromDb; my $ritaVarId = $posters->setCollateral('variantsJSON', 'variantId', 'new', { @@ -190,7 +191,8 @@ my $instance4 = WebGUI::Workflow::Instance->create($session, ); #break the asset $session->db->write('delete from asset where assetId=?', [$otherPosters->getId]); -is(WebGUI::Asset->new($session, $otherPosters->getId), undef, 'middle asset broken'); +$otherPosters->purgeCache; +dies_ok { WebGUI::Asset->newById($session, $otherPosters->getId); } 'middle asset broken'; $retVal = $instance4->run(); $retVal = $instance4->run(); From d57ee622ffde7f06d8d0c9bca11972ae3d5043ed Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 17:31:42 -0700 Subject: [PATCH 013/101] Fixed this test. --- t/Workflow/Activity/RemoveOldCarts.t | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/t/Workflow/Activity/RemoveOldCarts.t b/t/Workflow/Activity/RemoveOldCarts.t index 43f1d53b0..ad2ba7ba6 100644 --- a/t/Workflow/Activity/RemoveOldCarts.t +++ b/t/Workflow/Activity/RemoveOldCarts.t @@ -36,11 +36,13 @@ WebGUI::Test->tagsToRollback($tag); my $cart1 = WebGUI::Shop::Cart->create($session); +WebGUI::Test->addToCleanup($cart1); my $session2 = WebGUI::Session->open(WebGUI::Test->file); addToCleanup($session2); my $cart2 = WebGUI::Shop::Cart->create($session2); $cart2->update({creationDate => time()-10000}); +WebGUI::Test->addToCleanup($cart2); my @cartIds = $session->db->buildArray('select cartId from cart'); cmp_bag( @@ -69,9 +71,7 @@ my $workflow = WebGUI::Workflow->create($session, mode => 'realtime', }, ); -my $guard0 = cleanupGuard($workflow); -my $guard1 = cleanupGuard($cart1); -my $guard2 = cleanupGuard($cart2); +WebGUI::Test->addToCleanup($workflow); my $cartNuker = $workflow->addActivity('WebGUI::Workflow::Activity::RemoveOldCarts'); $cartNuker->set('cartTimeout', 3600); @@ -103,7 +103,3 @@ cmp_bag( [ $item1->getId, ], 'Deleted 1 item, the correct one' ); - -END { - $instance1->delete('skipNotify'); -} From 057260f13148867b16fbbb1c54bb4f56dc74ab04 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 18:04:19 -0700 Subject: [PATCH 014/101] fix a ->get conversion typo. --- lib/WebGUI/Asset/Wobject/Gallery.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/WebGUI/Asset/Wobject/Gallery.pm b/lib/WebGUI/Asset/Wobject/Gallery.pm index 3e8ef732b..e0201c02d 100644 --- a/lib/WebGUI/Asset/Wobject/Gallery.pm +++ b/lib/WebGUI/Asset/Wobject/Gallery.pm @@ -551,7 +551,7 @@ sub getAlbumIds { my $orderBy = $options->{ orderBy } ? $options->{ orderBy } : $self->viewListOrderBy - ? join( " ", $self->getviewListOrderBy, $self->viewListOrderDirection ) + ? join( " ", $self->viewListOrderBy, $self->viewListOrderDirection ) : "lineage ASC" ; From 5be85b9bed8617450cb154656021b891c7cca1f8 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 18:10:21 -0700 Subject: [PATCH 015/101] Cache update for a test --- t/Asset/Wobject/Survey.t | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/t/Asset/Wobject/Survey.t b/t/Asset/Wobject/Survey.t index 71581c481..481dddb0e 100644 --- a/t/Asset/Wobject/Survey.t +++ b/t/Asset/Wobject/Survey.t @@ -210,7 +210,7 @@ cmp_deeply(from_json($surveyEnd), { type => 'forward', url => '/getting_started' # Push revisionDate into the past because we can't have 2 revision dates with the same epoch (this is very hacky) $revisionDate--; $session->stow->deleteAll(); - WebGUI::Cache->new($session)->flush; + $session->cache->clear; $session->db->write('update Survey set revisionDate = ? where assetId = ?', [$revisionDate, $surveyId]); $session->db->write('update assetData set revisionDate = ? where assetId = ?', [$revisionDate, $surveyId]); $session->db->write('update wobject set revisionDate = ? where assetId = ?', [$revisionDate, $surveyId]); From 96108ffc96073618a12ef6c62dcde67761942606 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 18:14:17 -0700 Subject: [PATCH 016/101] Remove an old cache line. --- t/Group.t | 1 - 1 file changed, 1 deletion(-) diff --git a/t/Group.t b/t/Group.t index 0b549cc45..a0843a06b 100644 --- a/t/Group.t +++ b/t/Group.t @@ -435,7 +435,6 @@ cmp_bag($mobUsers, [map {$_->userId} @mob], 'verify SQL table built correctly'); is( $gY->databaseLinkId, 0, "Group Y's databaseLinkId is set to WebGUI"); $gY->dbQuery(q!select userId from myUserTable!); is( $session->stow->get('isInGroup'), undef, 'setting dbQuery clears cached isInGroup'); -#WebGUI::Cache->new($session, $gZ->getId)->delete(); ##Delete cached key for testing $session->cache->remove($gZ->getId); my @mobIds = map { $_->userId } @mob; From 95fe1e6d52051b3ad7b2359449b421dbf06d3a1e Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 18:14:27 -0700 Subject: [PATCH 017/101] Module use, and cache updates. --- lib/WebGUI/Asset/Wobject/SyndicatedContent.pm | 1 + t/Asset/Wobject/SyndicatedContent.t | 11 ++++------- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm b/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm index e268629ab..afaab1a20 100644 --- a/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm +++ b/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm @@ -15,6 +15,7 @@ use HTML::Entities; use WebGUI::Exception; use WebGUI::HTML; use WebGUI::International; +use LWP::UserAgent; use Moose; use WebGUI::Definition::Asset; diff --git a/t/Asset/Wobject/SyndicatedContent.t b/t/Asset/Wobject/SyndicatedContent.t index 84fb34d2d..232264dd0 100644 --- a/t/Asset/Wobject/SyndicatedContent.t +++ b/t/Asset/Wobject/SyndicatedContent.t @@ -24,7 +24,6 @@ use Test::More tests => 22; # increment this value for each test you create use Test::Deep; use WebGUI::Asset::Wobject::SyndicatedContent; use XML::FeedPP; -use WebGUI::Cache; my $session = WebGUI::Test->session; my %var; @@ -153,12 +152,11 @@ $syndicated_content->update({ hasTerms => 'WebGUI', }); -my $cache = WebGUI::Cache->new($session, $tbbUrl, 'RSS'); open my $rssFile, '<', WebGUI::Test->getTestCollateralPath('tbb.rss') or die "Unable to get RSS file"; my $rssContent = do { local $/; <$rssFile>; }; close $rssFile; -$cache->set($rssContent, 60); +$session->cache->set($tbbUrl.'RSS', $rssContent, 60); my $filteredFeed = $syndicated_content->generateFeed(); @@ -172,7 +170,7 @@ cmp_deeply( 'generateFeed: filters items based on the terms being in title, or description' ); -$cache->delete; +$session->cache->clear; #################################################################### # @@ -189,18 +187,17 @@ $syndicated_content->update({ maxHeadlines => 50, }); -my $cache = WebGUI::Cache->new($session, $oncpUrl, 'RSS'); open my $rssFile, '<', WebGUI::Test->getTestCollateralPath('oncp.xml') or die "Unable to get RSS file: oncp.xml"; my $rssContent = do { local $/; <$rssFile>; }; close $rssFile; -$cache->set($rssContent, 60); +$session->cache->set($oncpUrl.'RSS', $rssContent, 60); my $oddFeed1 = $syndicated_content->generateFeed(); my @oddItems = $oddFeed1->get_item(); is (@oddItems, 13, 'feed has items even without pubDates or links'); -$cache->delete; +$session->cache->clear; From 923e03f048fa8a2002fb4fbb00c3de1489f01f0e Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 19:03:20 -0700 Subject: [PATCH 018/101] Add a method for getViewCacheKey. Update number of tests. --- lib/WebGUI/Asset.pm | 67 +++++++++++++++++++++++++++------------------ t/Asset/Asset.t | 2 +- 2 files changed, 41 insertions(+), 28 deletions(-) diff --git a/lib/WebGUI/Asset.pm b/lib/WebGUI/Asset.pm index 3d9ae1fad..c8c86801a 100644 --- a/lib/WebGUI/Asset.pm +++ b/lib/WebGUI/Asset.pm @@ -845,26 +845,6 @@ sub getClassById { } -#------------------------------------------------------------------- - -=head2 getWwwCacheKey ( ) - -Returns a cache object specific to this asset, and whether or not the request is in SSL mode. - -=cut - -sub getWwwCacheKey { - my $self = shift; - my $session = $self->session; - my $method = shift; - my $cacheKey = join '_', @_, $self->getId; - if ($session->env->sslRequest) { - $cacheKey .= '_ssl'; - } - return $cacheKey; -} - - #------------------------------------------------------------------- =head2 getContainer ( ) @@ -883,6 +863,23 @@ sub getContainer { } } +#------------------------------------------------------------------- + +=head2 getContentLastModified + +Returns the overall modification time of the object and its content in Unix +epoch format, for the purpose of the Last-Modified HTTP header. Override this +for subclasses that contain content that is not solely lastModified property, +which gets updated every time update() is called. + +=cut + +sub getContentLastModified { + my $self = shift; + return $self->get("lastModified"); +} + + #------------------------------------------------------------------- =head2 getDefault ( session ) @@ -1711,18 +1708,34 @@ sub getUrl { #------------------------------------------------------------------- -=head2 getContentLastModified +=head2 getViewCacheKey ( ) -Returns the overall modification time of the object and its content in Unix -epoch format, for the purpose of the Last-Modified HTTP header. Override this -for subclasses that contain content that is not solely lastModified property, -which gets updated every time update() is called. +Returns the cache key for content generated by this Asset's view method. =cut -sub getContentLastModified { +sub getViewCacheKey { my $self = shift; - return $self->get("lastModified"); + return 'view_'.$self->assetId; +} + +#------------------------------------------------------------------- + +=head2 getWwwCacheKey ( ) + +Returns a cache object specific to this asset, and whether or not the request is in SSL mode. + +=cut + +sub getWwwCacheKey { + my $self = shift; + my $session = $self->session; + my $method = shift; + my $cacheKey = join '_', @_, $self->getId; + if ($session->env->sslRequest) { + $cacheKey .= '_ssl'; + } + return $cacheKey; } diff --git a/t/Asset/Asset.t b/t/Asset/Asset.t index ba5901b14..f88a910ca 100644 --- a/t/Asset/Asset.t +++ b/t/Asset/Asset.t @@ -35,7 +35,7 @@ my $session = WebGUI::Test->session; my @getTitleTests = getTitleTests($session); -plan tests => 110 +plan tests => 121 + 2*scalar(@getTitleTests) #same tests used for getTitle and getMenuTitle ; From 4c3b615f7a419ffda31abe781bc26e05e3781716 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 19:07:49 -0700 Subject: [PATCH 019/101] Update this test for exception handling. --- t/Asset/AssetLineage.t | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/t/Asset/AssetLineage.t b/t/Asset/AssetLineage.t index f34f94073..c6e605fc1 100644 --- a/t/Asset/AssetLineage.t +++ b/t/Asset/AssetLineage.t @@ -19,6 +19,7 @@ use WebGUI::User; use WebGUI::Asset; use Test::More tests => 94; # increment this value for each test you create use Test::Deep; +use Test::Exception; use Data::Dumper; # Test the methods in WebGUI::AssetLineage @@ -505,7 +506,7 @@ delete $cachedLineage->{$snippet4->get('lineage')}->{class}; my $snippet4 = WebGUI::Asset->newByLineage($session, $snippets[4]->get('lineage')); is ($snippet4->getId, $snippets[4]->getId, '... failing class cache forces lookup'); -is(WebGUI::Asset->newByLineage($session, 'notALineage'), undef, '... returns undef'); +dies_ok { WebGUI::Asset->newByLineage($session, 'notALineage') } '... throws an exception'; ok(!exists $session->stow->get('assetLineage')->{assetLineage}, '... no entry for the bad lineage in stow'); #################################################### From 8be35923e49b6a20df79f80b39b1bc5ea97c42b3 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 19:16:40 -0700 Subject: [PATCH 020/101] Drop session from get data generated by exportAssetData --- lib/WebGUI/AssetPackage.pm | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/WebGUI/AssetPackage.pm b/lib/WebGUI/AssetPackage.pm index 001fe41a4..d08d78327 100644 --- a/lib/WebGUI/AssetPackage.pm +++ b/lib/WebGUI/AssetPackage.pm @@ -48,6 +48,7 @@ Converts all the properties of this asset into a hash reference and then returns sub exportAssetData { my $self = shift; my %data = %{$self->get}; + delete $data{'session'}; my %hash = ( properties => \%data, storage=>[] ); return \%hash; } From a203ab48b69c2a0c18dc556b019f114ac181a902 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 19:17:05 -0700 Subject: [PATCH 021/101] Use a static time to remove 2 second sleep. Update test for new asset instanciators. --- t/Asset/AssetPackage.t | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/t/Asset/AssetPackage.t b/t/Asset/AssetPackage.t index 840d0a34e..4dc33b015 100644 --- a/t/Asset/AssetPackage.t +++ b/t/Asset/AssetPackage.t @@ -35,13 +35,15 @@ my $versionTag = WebGUI::VersionTag->getWorking($session); WebGUI::Test->tagsToRollback($versionTag); $versionTag->set({name=>"Asset Package test"}); +my $time = time() -2; + my $folder = $root->addChild({ url => 'testFolder', title => 'folder', menuTitle => 'folderMenuTitle', className => 'WebGUI::Asset::Wobject::Folder', isPackage => 1, -}); +}, undef, $time); my $targetFolder = $root->addChild({ url => 'targetFolder', @@ -56,7 +58,7 @@ my $subSnippet = $folder->addChild({ menuTitle => 'snippetMenuTitle', className => 'WebGUI::Asset::Snippet', snippet => 'A snippet of text', -}); +}, undef, $time); my $snippet = $root->addChild({ url => 'snip_snip', @@ -64,7 +66,7 @@ my $snippet = $root->addChild({ className => 'WebGUI::Asset::Snippet', snippet => 'Always upgrade to the latest version', isPackage => 1, -}); +}, undef, $time); my $packageAssetId = $folder->getId; $session->request->setup_body({ assetId => $packageAssetId }); @@ -75,7 +77,7 @@ is(scalar @{ $targetFolderChildren }, 0, 'target folder has no children'); $versionTag->commit; -sleep 2; +#sleep 2; my $storage = $snippet->exportPackage(); isa_ok($storage, 'WebGUI::Storage', 'exportPackage returns a WebGUI::Storage object'); @@ -110,15 +112,15 @@ my $newVersionTag = WebGUI::VersionTag->getWorking($session); WebGUI::Test->tagsToRollback($newVersionTag); $newVersionTag->commit; -my $newFolder = WebGUI::Asset->new($session, $folder->getId); +my $newFolder = WebGUI::Asset->newById($session, $folder->getId); ok(! $newFolder->get('isPackage'), 'Disabled isPackage in original folder asset'); sleep 1; -my $updatedSnippet = WebGUI::Asset->new($session, $snippet->getId); +my $updatedSnippet = WebGUI::Asset->newById($session, $snippet->getId); $root->importPackage($storage, { overwriteLatest => 1 }); -$updatedSnippet = WebGUI::Asset->new($session, $snippet->getId); +$updatedSnippet = WebGUI::Asset->newById($session, $snippet->getId); is($updatedSnippet->get('snippet'), 'Always upgrade to the latest version', 'importPackage: overwriteLatest causes revision dates to be ignored'); cmp_ok( $updatedSnippet->get('revisionDate'), '>', $snippetRev->get('revisionDate'), '... revisionDate check on imported package with overwriteLatest'); From ecf1c521f3affb4bed809f43548e1788a94ff634 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 21:03:59 -0700 Subject: [PATCH 022/101] Updates for Moose. --- lib/WebGUI/Asset/Wobject/EventManagementSystem.pm | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/WebGUI/Asset/Wobject/EventManagementSystem.pm b/lib/WebGUI/Asset/Wobject/EventManagementSystem.pm index 83a726f78..312ad068d 100644 --- a/lib/WebGUI/Asset/Wobject/EventManagementSystem.pm +++ b/lib/WebGUI/Asset/Wobject/EventManagementSystem.pm @@ -836,9 +836,9 @@ sub www_addSubmission { } } } - $form = WebGUI::Asset->newByDynamicClass($session,$formId); - if (!defined $form) { - $session->errorHandler->error(__PACKAGE__ . " - failed to instanciate asset with assetId $formId"); + $form = eval { WebGUI::Asset->newById($session, $formId); }; + if (Exception::Class->caught()) { + $session->errorHandler->error(__PACKAGE__ . " - failed to instanciate asset with assetId $formId"); } return $form->www_addSubmission; } @@ -1351,7 +1351,7 @@ sub www_getAllSubmissions { $tableInfo->{'records' } = []; for my $record ( @{ $p->getPageData } ) { - my $asset = WebGUI::Asset->newByDynamicClass( $session, $record->{assetId} ); + my $asset = WebGUI::Asset->newById( $session, $record->{assetId} ); my $lastReplyBy = $asset->get("lastReplyBy"); if ($lastReplyBy) { From 50b2b116eb427bd81be2ab1e6d44ba95ef4aa63e Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 21:04:12 -0700 Subject: [PATCH 023/101] Updated to Moose, and test updates. --- lib/WebGUI/Asset/EMSSubmissionForm.pm | 146 ++++++++++++-------------- t/Asset/EMSSubmissionForm.t | 1 + 2 files changed, 67 insertions(+), 80 deletions(-) diff --git a/lib/WebGUI/Asset/EMSSubmissionForm.pm b/lib/WebGUI/Asset/EMSSubmissionForm.pm index 085ecfd3d..b65f48b37 100644 --- a/lib/WebGUI/Asset/EMSSubmissionForm.pm +++ b/lib/WebGUI/Asset/EMSSubmissionForm.pm @@ -16,10 +16,70 @@ package WebGUI::Asset::EMSSubmissionForm; =cut use strict; +use Moose; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; + +define assetName => ['assetName','Asset_EMSSubmissionForm']; +define icon => 'EMSSubmissionForm.gif'; +define tableName => 'EMSSubmissionForm'; + +property canSubmitGroupId => ( + tab => "security", + fieldType => "group", + default => 2, + label => ["can submit group label", 'Asset_EMSSubmissionForm'], + hoverHelp => ["can submit group label help", 'Asset_EMSSubmissionForm'] + ); +property daysBeforeCleanup => ( + tab => "properties", + fieldType => "integer", + default => 7, + label => ["days before cleanup label", 'Asset_EMSSubmissionForm'], + hoverHelp => ["days before cleanup label help", 'Asset_EMSSubmissionForm'] + ); +property deleteCreatedItems => ( + tab => "properties", + fieldType => "yesNo", + default => undef, + label => ["delete created items label", 'Asset_EMSSubmissionForm'], + hoverHelp => ["delete created items label help", 'Asset_EMSSubmissionForm'] + ); +property submissionDeadline => ( + tab => "properties", + fieldType => "Date", + builder => '_default_submissionDeadline', + label => ["submission deadline label", 'Asset_EMSSubmissionForm'], + hoverHelp => ["submission deadline label help", 'Asset_EMSSubmissionForm'] + ); +sub _default_submissionDeadline { + return time() + ( 30 * 24 * 60 * 60 ); # 30 days +} +property pastDeadlineMessage => ( + tab => "properties", + fieldType => "HTMLArea", + builder => '_default_pastDeadlineMessage', + lazy => 1, + label => ["past deadline label", 'Asset_EMSSubmissionForm'], + hoverHelp => ["past deadline label help", 'Asset_EMSSubmissionForm'] + ); +sub _default_pastDeadlineMessage { + my $self = shift; + my $i18n = WebGUI::International->new($self->session, 'Asset_EMSSubmissionForm'); + return $i18n->get('past deadline message'); +} +property formDescription => ( + tab => "properties", + fieldType => "textarea", + default => '{ }', + label => ["form dscription label", 'Asset_EMSSubmissionForm'], + hoverHelp => ["form dscription label help", 'Asset_EMSSubmissionForm'] + ); + use Tie::IxHash; -use base 'WebGUI::Asset'; use JSON; use WebGUI::Utility; +with 'WebGUI::Role::Asset::AlwaysHidden'; =head1 NAME @@ -84,81 +144,6 @@ sub canSubmit { #------------------------------------------------------------------- -=head2 definition ( session, definition ) - -defines asset properties for New Asset instances. You absolutely need -this method in your new Assets. - -=head3 session - -=head3 definition - -A hash reference passed in from a subclass definition. - -=cut - -sub definition { - my $class = shift; - my $session = shift; - my $definition = shift; - my $i18n = WebGUI::International->new( $session, "Asset_EMSSubmissionForm" ); - tie my %properties, 'Tie::IxHash', ( - canSubmitGroupId => { - tab => "security", - fieldType => "group", - defaultValue => 2, - label => $i18n->get("can submit group label"), - hoverHelp => $i18n->get("can submit group label help") - }, - daysBeforeCleanup => { - tab => "properties", - fieldType => "integer", - defaultValue => 7, - label => $i18n->get("days before cleanup label"), - hoverHelp => $i18n->get("days before cleanup label help") - }, - deleteCreatedItems => { - tab => "properties", - fieldType => "yesNo", - defaultValue => undef, - label => $i18n->get("delete created items label"), - hoverHelp => $i18n->get("delete created items label help") - }, - submissionDeadline => { - tab => "properties", - fieldType => "Date", - defaultValue => time + ( 30 * 24 * 60 * 60 ) , # 30 days - label => $i18n->get("submission deadline label"), - hoverHelp => $i18n->get("submission deadline label help") - }, - pastDeadlineMessage => { - tab => "properties", - fieldType => "HTMLArea", - defaultValue => $i18n->get('past deadline message'), - label => $i18n->get("past deadline label"), - hoverHelp => $i18n->get("past deadline label help") - }, - formDescription => { - tab => "properties", - fieldType => "textarea", - defaultValue => '{ }', - label => $i18n->get("form dscription label"), - hoverHelp => $i18n->get("form dscription label help") - }, - ); - push @{$definition}, { - assetName => $i18n->get('assetName'), - icon => 'EMSSubmissionForm.gif', - autoGenerateForms => 1, - tableName => 'EMSSubmissionForm', - className => 'WebGUI::Asset::EMSSubmissionForm', - properties => \%properties, - }; - return $class->SUPER::definition( $session, $definition ); -} ## end sub definition - -#------------------------------------------------------------------- - =head2 ems returns the ems ansestor of this asset @@ -231,7 +216,7 @@ sub www_editSubmissionForm { } } } elsif( $assetId ne 'new' ) { - $self ||= WebGUI::Asset->newByDynamicClass($session,$assetId); + $self ||= WebGUI::Asset->newById($session, $assetId); if (!defined($self)) { $session->errorHandler->error(__PACKAGE__ . " - failed to instanciate asset with assetId $assetId"); } @@ -491,14 +476,15 @@ We overload the update method from WebGUI::Asset in order to handle file system =cut -sub update { +around update => sub { + my $orig = shift; my $self = shift; my $properties = shift; if( ref $properties->{formDescription} eq 'HASH' ) { $properties->{formDescription} = JSON->new->encode($properties->{formDescription}); } - $self->SUPER::update({%$properties, isHidden => 1}); -} + $self->$orig({%$properties}); +}; 1; diff --git a/t/Asset/EMSSubmissionForm.t b/t/Asset/EMSSubmissionForm.t index dd3d16fd4..615d2fabc 100644 --- a/t/Asset/EMSSubmissionForm.t +++ b/t/Asset/EMSSubmissionForm.t @@ -122,6 +122,7 @@ my $i18n = $ems->i18n; $versionTag->commit; $versionTag = WebGUI::VersionTag->getWorking($session); WebGUI::Test->tagsToRollback($versionTag); +$ems = $ems->cloneFromDb; my $id1 = $ems->getNextSubmissionId; my $id2 = $ems->getNextSubmissionId; From 7ba305109a62bd2690bc2cac0c1c520fcf7a8012 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 21:44:18 -0700 Subject: [PATCH 024/101] Set a trigger for the snippet. Update tests for snippet packing. --- lib/WebGUI/Asset/Snippet.pm | 1 + t/Asset/Snippet.t | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/WebGUI/Asset/Snippet.pm b/lib/WebGUI/Asset/Snippet.pm index 8567c0ad8..e10c1c8e7 100644 --- a/lib/WebGUI/Asset/Snippet.pm +++ b/lib/WebGUI/Asset/Snippet.pm @@ -34,6 +34,7 @@ property snippet => ( label => ['assetName','Asset_Snippet'], hoverHelp => ['snippet description','Asset_Snippet'], default => undef, + trigger => \&_trigger_snippet, ); sub _trigger_snippet { my $self = shift; diff --git a/t/Asset/Snippet.t b/t/Asset/Snippet.t index 5449c3315..fcfd363d5 100644 --- a/t/Asset/Snippet.t +++ b/t/Asset/Snippet.t @@ -16,7 +16,7 @@ use lib "$FindBin::Bin/../lib"; use WebGUI::Test; use WebGUI::Session; -use Test::More tests => 21; # increment this value for each test you create +use Test::More tests => 23; # increment this value for each test you create use Test::Exception; use WebGUI::Asset::Snippet; @@ -111,6 +111,12 @@ $snippet2->update({mimeType => 'text/javascript'}); $tag2->commit; addToCleanup($tag2); +$snippet2->snippet('uncompressable'); +is $snippet2->snippetPacked, 'uncompressable', 'packed snippet content was set'; + +$snippet2->snippet("two\n\nwords"); +is $snippet2->snippetPacked, "two words", '... and packed'; + open my $JSFILE, WebGUI::Test->getTestCollateralPath('jquery.js') or die "Unable to open jquery test collateral file: $!"; my $jquery; @@ -120,6 +126,7 @@ my $jquery; }; close $JSFILE; +$snippet2 = $snippet2->cloneFromDb; is $snippet2->get('snippetPacked'), undef, 'no packed content'; lives_ok { $snippet2->update({snippet => $jquery}); } 'did not die during packing jquery'; ok $snippet2->get('snippetPacked'), 'snippet content was packed'; From c2cbec2f18572bde2a037ed77e7b51803fd09d11 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 9 May 2010 22:31:57 -0700 Subject: [PATCH 025/101] Attempt to make this test more robust. --- t/VersionTag.t | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/t/VersionTag.t b/t/VersionTag.t index 34e3e659f..3cde71b7e 100644 --- a/t/VersionTag.t +++ b/t/VersionTag.t @@ -206,13 +206,16 @@ my $siteWideTag; $tag->clearWorking(); -ok(defined ($userTag = getWorking(1)), 'versionTagMode singlePerUser: reclaim version tag after clearWorking'); -is ($userTag->getId(), $userTagId, q{versionTagMode singlePerUser: reclaimed version tag has same id}); +my $gotTag = ok(defined ($userTag = getWorking(1)), 'versionTagMode singlePerUser: reclaim version tag after clearWorking'); +SKIP: { + skip 1, 'userTag not set' unless $gotTag; + is ($userTag->getId(), $userTagId, q{versionTagMode singlePerUser: reclaimed version tag has same id}); + $userTag->clearWorking(); +} #switch to sitewide mode -$userTag->clearWorking(); setSiteVersionTagMode($session, q{siteWide}); From 78426b7147182fb3b0133b52db27a8d55c4aa0ad Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Tue, 11 May 2010 22:07:05 -0700 Subject: [PATCH 026/101] Update test assets for export tests. --- t/Asset/AssetExportHtml.t | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/t/Asset/AssetExportHtml.t b/t/Asset/AssetExportHtml.t index 6445786fb..7d6acfdc3 100644 --- a/t/Asset/AssetExportHtml.t +++ b/t/Asset/AssetExportHtml.t @@ -188,6 +188,10 @@ my $grandChild = $firstChild->addChild({ }); $versionTag->commit; +foreach my $asset ($parent, $firstChild, $grandChild) { + $asset = $asset->cloneFromDb; +} + my $isExportable; # simple test first. the asset we're checking isn't exportable. should of course return 0. @@ -748,12 +752,12 @@ is($@, '', "exportAsHtml on parent does not throw an error"); ##Note, string com [ qw/ parent index.html /], ); -my $numberCreatedAll = scalar @createdFiles; -like($message, qr/Exported $numberCreatedAll pages/, "exportAsHtml on parent returns correct message"); - # turn them into Path::Class::File objects @shouldExist = map { Path::Class::File->new($exportPath, @{$_})->absolute->stringify } @createdFiles; +my $numberCreatedAll = scalar @createdFiles; +like($message, qr/Exported $numberCreatedAll pages/, "exportAsHtml on parent returns correct message"); + # ensure that the files that should exist do exist my @doExist; $exportPath->recurse( callback => sub { my $o = shift; $o->is_dir ? return : push @doExist, $o->absolute->stringify } ); From 2a6e50b478db215378ea39c151e92501f1856185 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Tue, 11 May 2010 22:13:25 -0700 Subject: [PATCH 027/101] Make this code readable. --- lib/WebGUI/Asset/EMSSubmissionForm.pm | 263 ++++++++++++++------------ 1 file changed, 143 insertions(+), 120 deletions(-) diff --git a/lib/WebGUI/Asset/EMSSubmissionForm.pm b/lib/WebGUI/Asset/EMSSubmissionForm.pm index b65f48b37..89c396508 100644 --- a/lib/WebGUI/Asset/EMSSubmissionForm.pm +++ b/lib/WebGUI/Asset/EMSSubmissionForm.pm @@ -172,131 +172,154 @@ optional set of possibly incorrect submission form params =cut sub www_editSubmissionForm { - my $this = shift; - my $self; - my $parent; - if( $this eq __PACKAGE__ ) { # called as constructor or menu - $parent = shift; - } else { - $self = $this; - $parent = $self->getParent; - } - my $params = shift || { }; - my $session = $parent->session; - my $i18n = WebGUI::International->new($session,'Asset_EventManagementSystem'); - my $assetId = $self ? $self->getId : $params->{assetId} || $session->form->get('assetId'); + my $this = shift; + my $self; + my $parent; + if ( $this eq __PACKAGE__ ) { # called as constructor or menu + $parent = shift; + } + else { + $self = $this; + $parent = $self->getParent; + } + my $params = shift || {}; + my $session = $parent->session; + my $i18n = WebGUI::International->new( $session, 'Asset_EventManagementSystem' ); + my $assetId = $self ? $self->getId : $params->{assetId} || $session->form->get('assetId'); - if( ! defined( $assetId ) ) { - my $res = $parent->getLineage(['children'],{ returnObjects => 1, - includeOnlyClasses => ['WebGUI::Asset::EMSSubmissionForm'], - } ); - if( scalar(@$res) == 1 ) { - $self = $res->[0]; - $assetId = $self->getId; - } else { - my $makeAnchorList =sub{ my $u=shift; my $n=shift; my $d=shift; - return qq{
  • $n
  • } } ; - my $listOfLinks = join '', ( map { - $makeAnchorList->( - $_->getQueueUrl, - $_->get('title'), - WebGUI::HTML::filter($_->get('description'),'all') - ) - } ( @$res ) ); - my $title = $i18n->get('select form to edit') ; - my $content = '

    ' . $title . '

      ' . $listOfLinks . '
    ' ; - if( $params->{asHashRef} ) { - return { text => $content, title => $title, } ; - } elsif( $session->form->get('asJson') ) { - $session->http->setMimeType( 'application/json' ); - return JSON->new->encode( { text => $content, title => $title, id => 'list' . rand } ); - } else { - $session->http->setMimeType( 'text/html' ); - return $parent->ems->processStyle( $content ); - } - } - } elsif( $assetId ne 'new' ) { - $self ||= WebGUI::Asset->newById($session, $assetId); - if (!defined($self)) { - $session->errorHandler->error(__PACKAGE__ . " - failed to instanciate asset with assetId $assetId"); - } + if ( !defined($assetId) ) { + my $res = $parent->getLineage( + ['children'], { + returnObjects => 1, + includeOnlyClasses => ['WebGUI::Asset::EMSSubmissionForm'], + } + ); + if ( scalar(@$res) == 1 ) { + $self = $res->[0]; + $assetId = $self->getId; } - my $asset = $self || $parent; - my $url = $asset->getUrl('func=editSubmissionFormSave'); - my $newform = WebGUI::HTMLForm->new( $session, action => $url ); - $newform->hidden(name => 'assetId', value => $assetId); - my @fieldNames = qw/title description startDate duration seatsAvailable location/; - my $fields; - my @defs = reverse @{WebGUI::Asset::EMSSubmission->definition($session)}; - for my $def ( @defs ) { - foreach my $fieldName ( @fieldNames ) { - my $properties = $def->{properties}; - if( defined $properties->{$fieldName} ) { - $fields->{$fieldName} = { %{$properties->{$fieldName}} }; # a simple first level copy - # field definitions don't contain their own name, we will need it later on - $fields->{$fieldName}{fieldId} = $fieldName; - }; - } - } - for my $metaField ( @{$parent->getEventMetaFields} ) { - push @fieldNames, $metaField->{fieldId}; - $fields->{$metaField->{fieldId}} = { %$metaField }; # a simple first level copy - # meta fields call it data type, we copy it to simplify later on - $fields->{$metaField->{fieldId}}{fieldType} = $metaField->{dataType}; - $fields->{$metaField->{fieldId}}{hoverHelp} = $metaField->{helpText}; - } - $newform->hidden( name => 'fieldNames', value => join( ' ', @fieldNames ) ); - @defs = reverse @{WebGUI::Asset::EMSSubmissionForm->definition($session)}; - for my $def ( @defs ) { - my $properties = $def->{properties}; - for my $fieldName ( qw/title menuTitle url description canSubmitGroupId daysBeforeCleanup - deleteCreatedItems submissionDeadline pastDeadlineMessage/ ) { - if( defined $properties->{$fieldName} ) { - my %fieldParams = %{$properties->{$fieldName}}; - $fieldParams{name} = $fieldName; - $fieldParams{value} = $params->{$fieldName} || $self ? $self->get($fieldName) : undef ; - $newform->dynamicField(%fieldParams); - } - } + else { + my $makeAnchorList = sub { + my $u = shift; + my $n = shift; + my $d = shift; + return qq{
  • $n
  • }; + }; + my $listOfLinks = join '', ( + map { + $makeAnchorList->( + $_->getQueueUrl, $_->get('title'), WebGUI::HTML::filter( $_->get('description'), 'all' ) + ) + } (@$res) + ); + my $title = $i18n->get('select form to edit'); + my $content = '

    ' . $title . '

      ' . $listOfLinks . '
    '; + if ( $params->{asHashRef} ) { + return { text => $content, title => $title, }; + } + elsif ( $session->form->get('asJson') ) { + $session->http->setMimeType('application/json'); + return JSON->new->encode( { text => $content, title => $title, id => 'list' . rand } ); + } + else { + $session->http->setMimeType('text/html'); + return $parent->ems->processStyle($content); + } + } ## end else [ if ( scalar(@$res) == ...)] + } ## end if ( !defined($assetId...)) + elsif ( $assetId ne 'new' ) { + $self ||= WebGUI::Asset->newById( $session, $assetId ); + if ( !defined($self) ) { + $session->errorHandler->error( __PACKAGE__ . " - failed to instanciate asset with assetId $assetId" ); } + } + my $asset = $self || $parent; + my $url = $asset->getUrl('func=editSubmissionFormSave'); + my $newform = WebGUI::HTMLForm->new( $session, action => $url ); + $newform->hidden( name => 'assetId', value => $assetId ); + my @fieldNames = qw/title description startDate duration seatsAvailable location/; + my $fields; + my @defs = reverse @{ WebGUI::Asset::EMSSubmission->definition($session) }; - my $formDescription = $params->{formDescription} || $self ? $self->getFormDescription : { }; - for my $fieldId ( @fieldNames ) { - next if $fieldId eq 'submissionStatus'; - my $field = $fields->{$fieldId}; - $newform->yesNo( - label => $field->{label}, - name => $field->{fieldId} . '_yesNo', - defaultValue => 0, - value => $formDescription->{$field->{fieldId}}, - ); - } - $newform->submit; - my $title = $assetId eq 'new' ? $i18n->get('new form') || 'new' : $asset->get('title'); - if( $params->{asHashRef} ) { - ; # not setting mimie type - } elsif( $session->form->get('asJson') ) { - $session->http->setMimeType( 'application/json' ); - } else { - $session->http->setMimeType( 'text/html' ); - } - my $content = $asset->processTemplate({ - errors => $params->{errors} || [], - isDynamic => $session->form->get('asJson') || 0, - backUrl => $parent->getUrl, - pageTitle => $title, - pageForm => $newform->print, - },$parent->get('eventSubmissionTemplateId')); - WebGUI::Macro::process( $session, \$content ); - if( $params->{asHashRef} ) { - return { text => $content, title => $title }; - } elsif( $session->form->get('asJson') ) { - return JSON->new->encode( { text => $content, title => $title, id => $assetId ne 'new' ? $assetId : 'new' . rand } ); - } else { - return $asset->ems->processStyle( $content ); - } + for my $def (@defs) { + foreach my $fieldName (@fieldNames) { + my $properties = $def->{properties}; + if ( defined $properties->{$fieldName} ) { + $fields->{$fieldName} = { %{ $properties->{$fieldName} } }; # a simple first level copy + # field definitions don't contain their own name, we will need it later on + $fields->{$fieldName}{fieldId} = $fieldName; + } + } + } + for my $metaField ( @{ $parent->getEventMetaFields } ) { + push @fieldNames, $metaField->{fieldId}; + $fields->{ $metaField->{fieldId} } = {%$metaField}; # a simple first level copy + # meta fields call it data type, we copy it to simplify later on + $fields->{ $metaField->{fieldId} }{fieldType} = $metaField->{dataType}; + $fields->{ $metaField->{fieldId} }{hoverHelp} = $metaField->{helpText}; + } + $newform->hidden( name => 'fieldNames', value => join( ' ', @fieldNames ) ); + @defs = reverse @{ WebGUI::Asset::EMSSubmissionForm->definition($session) }; + for my $def (@defs) { + my $properties = $def->{properties}; + for my $fieldName ( + qw/title menuTitle url description canSubmitGroupId daysBeforeCleanup + deleteCreatedItems submissionDeadline pastDeadlineMessage/ + ) + { + if ( defined $properties->{$fieldName} ) { + my %fieldParams = %{ $properties->{$fieldName} }; + $fieldParams{name} = $fieldName; + $fieldParams{value} = $params->{$fieldName} || $self ? $self->get($fieldName) : undef; + $newform->dynamicField(%fieldParams); + } + } + } -} + my $formDescription = $params->{formDescription} || $self ? $self->getFormDescription : {}; + for my $fieldId (@fieldNames) { + next if $fieldId eq 'submissionStatus'; + my $field = $fields->{$fieldId}; + $newform->yesNo( + label => $field->{label}, + name => $field->{fieldId} . '_yesNo', + defaultValue => 0, + value => $formDescription->{ $field->{fieldId} }, + ); + } + $newform->submit; + my $title = $assetId eq 'new' ? $i18n->get('new form') || 'new' : $asset->get('title'); + if ( $params->{asHashRef} ) { + ; # not setting mimie type + } + elsif ( $session->form->get('asJson') ) { + $session->http->setMimeType('application/json'); + } + else { + $session->http->setMimeType('text/html'); + } + my $content = $asset->processTemplate( { + errors => $params->{errors} || [], + isDynamic => $session->form->get('asJson') || 0, + backUrl => $parent->getUrl, + pageTitle => $title, + pageForm => $newform->print, + }, + $parent->get('eventSubmissionTemplateId') + ); + WebGUI::Macro::process( $session, \$content ); + if ( $params->{asHashRef} ) { + return { text => $content, title => $title }; + } + elsif ( $session->form->get('asJson') ) { + return JSON->new->encode( + { text => $content, title => $title, id => $assetId ne 'new' ? $assetId : 'new' . rand } ); + } + else { + return $asset->ems->processStyle($content); + } + +} ## end sub www_editSubmissionForm #------------------------------------------------------------------- From 7f23c286da0c255ebe9983595f55368f73c799b2 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 13:50:04 -0700 Subject: [PATCH 028/101] Change newByDynamicClass to newById. --- lib/WebGUI/Asset/EMSSubmission.pm | 4 ++-- lib/WebGUI/Asset/File/GalleryFile.pm | 8 ++++---- lib/WebGUI/Asset/WikiPage.pm | 4 ++-- lib/WebGUI/Asset/Wobject/GalleryAlbum.pm | 12 ++++++------ 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/lib/WebGUI/Asset/EMSSubmission.pm b/lib/WebGUI/Asset/EMSSubmission.pm index 48e265839..f7e819a5f 100644 --- a/lib/WebGUI/Asset/EMSSubmission.pm +++ b/lib/WebGUI/Asset/EMSSubmission.pm @@ -346,8 +346,8 @@ sub www_editSubmission { my $assetId = $self ? $self->getId : $params->{assetId} || $session->form->get('assetId') || 'new'; if( $assetId ne 'new' ) { - $self ||= WebGUI::Asset->newByDynamicClass($session,$assetId); - if (!defined $self) { + $self ||= eval { WebGUI::Asset->newById($session,$assetId); }; + if (Exception::Class->caught()) { $session->errorHandler->error(__PACKAGE__ . " - failed to instanciate asset with assetId $assetId"); } } diff --git a/lib/WebGUI/Asset/File/GalleryFile.pm b/lib/WebGUI/Asset/File/GalleryFile.pm index a22eb2292..78c59c720 100644 --- a/lib/WebGUI/Asset/File/GalleryFile.pm +++ b/lib/WebGUI/Asset/File/GalleryFile.pm @@ -435,7 +435,7 @@ sub getFirstFile { my $allFileIds = $self->getParent->getFileIds; return undef unless @{ $allFileIds }; - return WebGUI::Asset->newByDynamicClass( $self->session, shift @{ $allFileIds }); + return WebGUI::Asset->newById( $self->session, shift @{ $allFileIds }); } #---------------------------------------------------------------------------- @@ -452,7 +452,7 @@ sub getLastFile { my $allFileIds = $self->getParent->getFileIds; return undef unless @{ $allFileIds }; - return WebGUI::Asset->newByDynamicClass( $self->session, pop @{ $allFileIds }); + return WebGUI::Asset->newById( $self->session, pop @{ $allFileIds }); } #---------------------------------------------------------------------------- @@ -469,7 +469,7 @@ sub getNextFile { return $self->{_nextFile} if $self->{_nextFile}; my $nextId = $self->getParent->getNextFileId( $self->getId ); return undef unless $nextId; - $self->{_nextFile} = WebGUI::Asset->newByDynamicClass( $self->session, $nextId ); + $self->{_nextFile} = WebGUI::Asset->newById( $self->session, $nextId ); return $self->{_nextFile}; } @@ -487,7 +487,7 @@ sub getPreviousFile { return $self->{_previousFile} if $self->{_previousFile}; my $previousId = $self->getParent->getPreviousFileId( $self->getId ); return undef unless $previousId; - $self->{_previousFile} = WebGUI::Asset->newByDynamicClass( $self->session, $previousId ); + $self->{_previousFile} = WebGUI::Asset->newById( $self->session, $previousId ); return $self->{_previousFile}; } diff --git a/lib/WebGUI/Asset/WikiPage.pm b/lib/WebGUI/Asset/WikiPage.pm index caa5ac6a7..a84f71628 100644 --- a/lib/WebGUI/Asset/WikiPage.pm +++ b/lib/WebGUI/Asset/WikiPage.pm @@ -289,8 +289,8 @@ sub getTemplateVars { }); PAGE: foreach my $assetId (@{ $paginator->getPageData }) { next PAGE if $assetId->{assetId} eq $self->getId; - my $asset = WebGUI::Asset->newByDynamicClass($session, $assetId->{assetId}); - next PAGE unless $asset; + my $asset = eval { WebGUI::Asset->newById($session, $assetId->{assetId}); }; + next PAGE if Exception::Class->caught(); push @keyword_pages, { title => $asset->getTitle, url => $asset->getUrl, diff --git a/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm b/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm index 9251d2efe..b2fc69c27 100644 --- a/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm +++ b/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm @@ -1247,10 +1247,10 @@ sub _moveFileAjaxRequest { # Get Id of target photo and instantiate asset my $targetId = $args->{target}; - my $target = WebGUI::Asset->newByDynamicClass( $session, $targetId ); + my $target = eval { WebGUI::Asset->newById( $session, $targetId ); }; # Return if target photo could not be instantiated - unless ( $target ) { + if ( Exception::Class->caught() ) { $session->log->error("Couldn't move file '$targetId' because we couldn't instantiate it."); $result{ errMessage } = "ID of target file seems to be invalid."; return \%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->newByDynamicClass( $session, $destId ); + $dest = WebGUI::Asset->newById( $session, $destId ); # Return if destination file could not be instantiated - unless ( $dest ) { + if ( Expeption::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; @@ -1286,14 +1286,14 @@ sub _moveFileAjaxRequest { # Get ID of next sibling $destId = $self->getNextFileId( $destId ); # Instantiate next sibling - $dest = WebGUI::Asset->newByDynamicClass( $session, $destId ); + $dest = WebGUI::Asset->newById( $session, $destId ); } # Check for use of before argument when increasing the rank if ( $args->{before} && $target->getRank() < $dest->getRank() ) { # Get ID of previous sibling $destId = $self->getPreviousFileId( $destId ); # Instantiate previous sibling - $dest = WebGUI::Asset->newByDynamicClass( $session, $destId ); + $dest = WebGUI::Asset->newById( $session, $destId ); } # Update rank of target photo From c892e51c9bad0cb0d29ec0c535e1d1464f624fb6 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 13:58:32 -0700 Subject: [PATCH 029/101] Update tests for wg8 and better cleanup. --- t/Asset/File/GalleryFile/Photo/00base.t | 15 +++------------ t/Asset/File/GalleryFile/Photo/comment.t | 11 +---------- t/Asset/File/GalleryFile/Photo/download.t | 12 +----------- 3 files changed, 5 insertions(+), 33 deletions(-) diff --git a/t/Asset/File/GalleryFile/Photo/00base.t b/t/Asset/File/GalleryFile/Photo/00base.t index 5fcb8b76e..bca45f0a3 100644 --- a/t/Asset/File/GalleryFile/Photo/00base.t +++ b/t/Asset/File/GalleryFile/Photo/00base.t @@ -18,12 +18,14 @@ use Scalar::Util; use WebGUI::Test; use WebGUI::Session; use Test::More; +use Test::Exception; #---------------------------------------------------------------------------- # Init my $session = WebGUI::Test->session; my $node = WebGUI::Asset->getImportNode($session); my $versionTag = WebGUI::VersionTag->getWorking($session); +WebGUI::Test->addToCleanup($versionTag); $versionTag->set({name=>"Photo Test"}); @@ -90,15 +92,4 @@ is( my $properties = $photo->get; $photo->purge; -is( - WebGUI::Asset->newByDynamicClass($session, $properties->{assetId}), undef, - "Photo no longer able to be instanciated", -); - -#---------------------------------------------------------------------------- -# Cleanup -END { - $versionTag->rollback; -} - - +dies_ok { WebGUI::Asset->newById($session, $properties->{assetId}) } "Photo no longer able to be instanciated"; diff --git a/t/Asset/File/GalleryFile/Photo/comment.t b/t/Asset/File/GalleryFile/Photo/comment.t index acabceecd..0690d4759 100644 --- a/t/Asset/File/GalleryFile/Photo/comment.t +++ b/t/Asset/File/GalleryFile/Photo/comment.t @@ -31,6 +31,7 @@ my $node = WebGUI::Asset->getImportNode($session); my @versionTags = (); push @versionTags, WebGUI::VersionTag->getWorking($session); $versionTags[-1]->set({name=>"Photo Test, add Gallery, Album and 1 Photo"}); +WebGUI::Test->addToCleanup($versionTags[-1]); my @addArguments = ( undef, undef, { skipAutoCommitWorkflows => 1 } ); my $gallery @@ -326,13 +327,3 @@ TODO: { # TODO ok( 0, "Visitor has their IP logged in visitorIp field" ); } - -#---------------------------------------------------------------------------- -# Cleanup -END { - foreach my $versionTag (@versionTags) { - $versionTag->rollback; - } -}; - - diff --git a/t/Asset/File/GalleryFile/Photo/download.t b/t/Asset/File/GalleryFile/Photo/download.t index 6fa59fcd5..3d97b6d8b 100644 --- a/t/Asset/File/GalleryFile/Photo/download.t +++ b/t/Asset/File/GalleryFile/Photo/download.t @@ -29,7 +29,7 @@ my $node = WebGUI::Asset->getImportNode($session); my @versionTags = (); push @versionTags, WebGUI::VersionTag->getWorking($session); $versionTags[-1]->set({name=>"Photo Test, add Gallery, Album and 1 Photo"}); -my $versionTag = WebGUI::VersionTag->getWorking($session); +WebGUI::Test->addToCleanup($versionTags[-1]); my $gallery = $node->addChild({ @@ -84,13 +84,3 @@ ok( "getDownloadFileUrl croaks if resolution doesn't exist", ); - -#---------------------------------------------------------------------------- -# Cleanup -END { - foreach my $versionTag (@versionTags) { - $versionTag->rollback; - } -} - - From 8a9e4c73c1c2029dbd3bd7de5a007b61a3ab2c66 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 14:06:13 -0700 Subject: [PATCH 030/101] Remove dead code in the Photo asset. --- lib/WebGUI/Asset/File/GalleryFile/Photo.pm | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/WebGUI/Asset/File/GalleryFile/Photo.pm b/lib/WebGUI/Asset/File/GalleryFile/Photo.pm index c288a6f3b..12d4eecf6 100644 --- a/lib/WebGUI/Asset/File/GalleryFile/Photo.pm +++ b/lib/WebGUI/Asset/File/GalleryFile/Photo.pm @@ -93,7 +93,6 @@ override applyConstraints => sub { # Update the asset's size and make a thumbnail my $maxImageSize = $gallery->imageViewSize || $self->session->setting->get("maxImageSize"); - my $parameters = $self->parameters; my $storage = $self->getStorageLocation; my $file = $self->filename; From 7db971d274081a0f3dc0798c5b0599da57a60cb4 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 14:07:27 -0700 Subject: [PATCH 031/101] Better clean-up. --- t/Asset/File/GalleryFile/Photo/exif.t | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/t/Asset/File/GalleryFile/Photo/exif.t b/t/Asset/File/GalleryFile/Photo/exif.t index 303065b0b..f1a0f2390 100644 --- a/t/Asset/File/GalleryFile/Photo/exif.t +++ b/t/Asset/File/GalleryFile/Photo/exif.t @@ -27,6 +27,7 @@ my $session = WebGUI::Test->session; my $node = WebGUI::Asset->getImportNode($session); my $versionTag = WebGUI::VersionTag->getWorking($session); $versionTag->set({name=>"Photo Test"}); +WebGUI::Test->addToCleanup($versionTag); my $gallery = $node->addChild({ className => "WebGUI::Asset::Wobject::Gallery", @@ -61,13 +62,6 @@ for my $key ( qw{ Directory } ) { delete $exif->{ $key }; } - -#---------------------------------------------------------------------------- -# Cleanup -END { - $versionTag->rollback(); -} - #---------------------------------------------------------------------------- # Tests plan tests => 2; From 7258e11e7e5d02dccd3d2440b4c39734b28cc061 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 15:28:45 -0700 Subject: [PATCH 032/101] Move Shortcut definition methods to Moose methods. --- lib/WebGUI/Asset/Shortcut.pm | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/lib/WebGUI/Asset/Shortcut.pm b/lib/WebGUI/Asset/Shortcut.pm index f49af90c7..0f23d6e67 100644 --- a/lib/WebGUI/Asset/Shortcut.pm +++ b/lib/WebGUI/Asset/Shortcut.pm @@ -497,9 +497,9 @@ sub getOverrides { my $orig = $self->getShortcutOriginal; if (defined $orig) { unless ( exists $orig->{_propertyDefinitions}) { - my %properties; - foreach my $definition (@{$orig->definition($self->session)}) { - %properties = (%properties, %{$definition->{properties}}); + my %properties; + foreach my $property ($orig->getProperties) { + $properties{$property} = $orig->getFormProperties($property); } $orig->{_propertyDefinitions} = \%properties; } @@ -1150,14 +1150,7 @@ sub www_editOverride { ); # Fetch the parameters for the dynamic field. - my (%params, %props); - foreach my $def (@{$self->getShortcutOriginal->definition($self->session)}) { - %props = (%props,%{$def->{properties}}); - } - foreach my $key (keys %{$props{$fieldName}}) { - next if ($key eq "tab"); - $params{$key} = $props{$fieldName}{$key}; - } + my %params = %{ $self->getShortcutOriginal->getFormProperties($fieldName) }; $params{value} = $origValue; $params{name} = $fieldName; $params{label} = $params{label} || $i18n->get("Edit Field Directly"); From 4fef8cb48694226e3cfc469ac51f10846bf7751a Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 15:41:51 -0700 Subject: [PATCH 033/101] Fix a bad sort. Clarify some POD in the Photo. --- lib/WebGUI/Asset/File/GalleryFile/Photo.pm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/WebGUI/Asset/File/GalleryFile/Photo.pm b/lib/WebGUI/Asset/File/GalleryFile/Photo.pm index 12d4eecf6..d9e0a9b9d 100644 --- a/lib/WebGUI/Asset/File/GalleryFile/Photo.pm +++ b/lib/WebGUI/Asset/File/GalleryFile/Photo.pm @@ -213,7 +213,7 @@ sub getExifData { =head2 getResolutions ( ) Get an array reference of download resolutions that exist for this image. -Does not include the web view image or the thumbnail image. +Does not include the web view image or the thumbnail images. =cut @@ -222,7 +222,7 @@ sub getResolutions { my $storage = $self->getStorageLocation; # Return a list not including the web view image. - return [ sort { $a <=> $b } grep { $_ ne $self->filename } @{ $storage->getFiles } ]; + return [ sort { $a cmp $b } grep { $_ ne $self->filename } @{ $storage->getFiles } ]; } #---------------------------------------------------------------------------- From 420cc3e84310c677a7bf00f8833eff467be63453 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 15:43:16 -0700 Subject: [PATCH 034/101] A bunch of fixed Photo tests. --- .../File/GalleryFile/Photo/makeResolutions.t | 18 ++++-------- t/Asset/File/GalleryFile/Photo/makeShortcut.t | 28 +++++++++++-------- t/Asset/File/GalleryFile/Photo/permissions.t | 1 + t/Asset/File/GalleryFile/Photo/view.t | 10 +++---- 4 files changed, 28 insertions(+), 29 deletions(-) diff --git a/t/Asset/File/GalleryFile/Photo/makeResolutions.t b/t/Asset/File/GalleryFile/Photo/makeResolutions.t index 415124e38..f2b3dab24 100644 --- a/t/Asset/File/GalleryFile/Photo/makeResolutions.t +++ b/t/Asset/File/GalleryFile/Photo/makeResolutions.t @@ -62,6 +62,7 @@ $photo skipAutoCommitWorkflows => 1, }); $versionTags[-1]->commit; +WebGUI::Test->addToCleanup($versionTags[-1]); $photo->getStorageLocation->addFileFromFilesystem( WebGUI::Test->getTestCollateralPath('page_title.jpg') ); $photo->update({ filename => 'page_title.jpg' }); @@ -86,6 +87,7 @@ TODO: { # Array of resolutions passed to makeResolutions overrides defaults from # parent asset push @versionTags, WebGUI::VersionTag->getWorking($session); +WebGUI::Test->addToCleanup($versionTags[-1]); $gallery = $node->addChild({ className => "WebGUI::Asset::Wobject::Gallery", @@ -139,8 +141,9 @@ TODO: { # makeResolutions allows API to specify resolutions to make as array reference # argument push @versionTags, WebGUI::VersionTag->getWorking($session); +WebGUI::Test->addToCleanup($versionTags[-1]); $photo - = $node->addChild({ + = $album->addChild({ className => "WebGUI::Asset::File::GalleryFile::Photo", }, undef, @@ -176,8 +179,9 @@ TODO: { #---------------------------------------------------------------------------- # makeResolutions throws a warning on an invalid resolution but keeps going push @versionTags, WebGUI::VersionTag->getWorking($session); +WebGUI::Test->addToCleanup($versionTags[-1]); $photo - = $node->addChild({ + = $album->addChild({ className => "WebGUI::Asset::File::GalleryFile::Photo", }, undef, @@ -220,13 +224,3 @@ $photo->update({ filename => 'page_title.jpg' }); "makeResolutions still makes valid resolutions when invalid resolutions given", ); } - -#---------------------------------------------------------------------------- -# Cleanup -END { - foreach my $versionTag (@versionTags) { - $versionTag->rollback; - } -} - - diff --git a/t/Asset/File/GalleryFile/Photo/makeShortcut.t b/t/Asset/File/GalleryFile/Photo/makeShortcut.t index eb74e6ce9..5f6fa158a 100644 --- a/t/Asset/File/GalleryFile/Photo/makeShortcut.t +++ b/t/Asset/File/GalleryFile/Photo/makeShortcut.t @@ -20,7 +20,6 @@ use WebGUI::Test; use WebGUI::Session; use Test::More; use Test::Deep; -use WebGUI::Test::Maker::HTML; use WebGUI::Asset::File::GalleryFile::Photo; #---------------------------------------------------------------------------- @@ -29,13 +28,28 @@ my $session = WebGUI::Test->session; my $node = WebGUI::Asset->getImportNode($session); my $versionTag = WebGUI::VersionTag->getWorking($session); $versionTag->set({name=>"Photo Test"}); -my $maker = WebGUI::Test::Maker::HTML->new; +WebGUI::Test->addToCleanup($versionTag); my $otherParent = $node->addChild({ className => "WebGUI::Asset::Wobject::Layout", }); -my $photo +my $gallery = $node->addChild({ + className => "WebGUI::Asset::Wobject::Gallery", + imageResolutions => "1600x1200\n1024x768\n800x600\n640x480", + }); +my $album + = $gallery->addChild({ + className => "WebGUI::Asset::Wobject::GalleryAlbum", + }, + undef, + undef, + { + skipAutoCommitWorkflows => 1, + }); + +my $photo + = $album->addChild({ className => "WebGUI::Asset::File::GalleryFile::Photo", userDefined1 => "ORIGINAL", }, @@ -118,11 +132,3 @@ cmp_deeply( #---------------------------------------------------------------------------- # www_makeShortcut - -#---------------------------------------------------------------------------- -# Cleanup -END { - $versionTag->rollback(); -} - - diff --git a/t/Asset/File/GalleryFile/Photo/permissions.t b/t/Asset/File/GalleryFile/Photo/permissions.t index ee4f58c3e..62c3d270d 100644 --- a/t/Asset/File/GalleryFile/Photo/permissions.t +++ b/t/Asset/File/GalleryFile/Photo/permissions.t @@ -72,6 +72,7 @@ my $photo { skipAutoCommitWorkflows => 1, }); +$versionTag->commit; my $photo2 = $photo->cloneFromDb; my $album2 = $album->cloneFromDb; diff --git a/t/Asset/File/GalleryFile/Photo/view.t b/t/Asset/File/GalleryFile/Photo/view.t index 97b3eb317..b98554c7c 100644 --- a/t/Asset/File/GalleryFile/Photo/view.t +++ b/t/Asset/File/GalleryFile/Photo/view.t @@ -73,6 +73,10 @@ my $nextPhoto skipAutoCommitWorkflows => 1, }); $versionTag->commit; +foreach my $asset ($gallery, $album) { + $asset = $asset->cloneFromDb; +} +WebGUI::Test->addToCleanup($versionTag); $photo->setFile( WebGUI::Test->getTestCollateralPath('page_title.jpg') ); #---------------------------------------------------------------------------- @@ -148,9 +152,3 @@ cmp_deeply( $testTemplateVars, "getTemplateVars is correct and complete", ); - -#---------------------------------------------------------------------------- -# Cleanup -END { - $versionTag->rollback(); -} From 427fd5e53a636315df52bcead6d375153354c691 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 19:46:47 -0700 Subject: [PATCH 035/101] Removing more dead code. There is no maxImageSize property. --- lib/WebGUI/Asset/File/Image.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/WebGUI/Asset/File/Image.pm b/lib/WebGUI/Asset/File/Image.pm index e80ab2fc0..6720a909a 100644 --- a/lib/WebGUI/Asset/File/Image.pm +++ b/lib/WebGUI/Asset/File/Image.pm @@ -93,7 +93,7 @@ override applyConstraints => sub { my $self = shift; my $options = shift; super(); - my $maxImageSize = $options->{maxImageSize} || $self->maxImageSize || $self->session->setting->get("maxImageSize"); + my $maxImageSize = $options->{maxImageSize} || $self->session->setting->get("maxImageSize"); my $thumbnailSize = $options->{thumbnailSize} || $self->thumbnailSize || $self->session->setting->get("thumbnailSize"); my $storage = $self->getStorageLocation; my $file = $self->filename; From c74894321d97a4aa15fc57b824b081c1ea4fc7a0 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 19:47:08 -0700 Subject: [PATCH 036/101] Update these tests for file locations and better clean-up. --- t/Asset/File/Image/setfile.t | 7 +------ t/Asset/File/setfile.t | 11 ++--------- 2 files changed, 3 insertions(+), 15 deletions(-) diff --git a/t/Asset/File/Image/setfile.t b/t/Asset/File/Image/setfile.t index 0792b0699..a9d8a9030 100644 --- a/t/Asset/File/Image/setfile.t +++ b/t/Asset/File/Image/setfile.t @@ -26,6 +26,7 @@ my $session = WebGUI::Test->session; my $node = WebGUI::Asset->getImportNode($session); my $versionTag = WebGUI::VersionTag->getWorking($session); $versionTag->set({name=>"Image Test"}); +WebGUI::Test->addToCleanup($versionTag); my $image = $node->addChild({ className => "WebGUI::Asset::File::Image", @@ -54,9 +55,3 @@ ok( "Thumbnail file exists on the filesystem", ); - -#---------------------------------------------------------------------------- -# Cleanup -END { - $versionTag->rollback(); -} diff --git a/t/Asset/File/setfile.t b/t/Asset/File/setfile.t index 88f61f1a7..a049ce9f5 100644 --- a/t/Asset/File/setfile.t +++ b/t/Asset/File/setfile.t @@ -25,6 +25,7 @@ my $session = WebGUI::Test->session; my $node = WebGUI::Asset->getImportNode($session); my $versionTag = WebGUI::VersionTag->getWorking($session); $versionTag->set({name=>"File Test"}); +WebGUI::Test->addToCleanup($versionTag); my $file = $node->addChild({ className => "WebGUI::Asset::File", @@ -46,18 +47,10 @@ ok( #---------------------------------------------------------------------------- # setFile allows file path argument and adds the file # plan tests => 1 -$file->setFile( WebGUI::Test->getTestCollateralPath("WebGUI.pm") ); +$file->setFile( WebGUI::Test->getTestCollateralPath("International/lib/WebGUI/i18n/PigLatin/WebGUI.pm") ); my $storage = $file->getStorageLocation; is_deeply( $storage->getFiles, ['WebGUI.pm'], "Storage location contains only the file we added", ); - - -#---------------------------------------------------------------------------- -# Cleanup -END { - $versionTag->rollback(); -} - From 5140ece7317abc5faea45a0fd568d08e64543e06 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 20:02:26 -0700 Subject: [PATCH 037/101] Large batch of test fixes, most for newByDynamicClass -> newById --- t/Asset/EMSSubmissionForm.t | 4 ++-- t/Asset/File/GalleryFile/Photo/edit.t | 4 ++-- t/Asset/Post.t | 3 ++- t/Asset/Post/Thread.t | 2 ++ t/Asset/Post/Thread/getAdjacentThread.t | 19 +++++++++---------- t/Asset/Post/Thread/permission.t | 6 +++--- t/Asset/Post/permission.t | 6 +++--- t/Asset/Sku/ProductCollateral.t | 2 +- t/Asset/Wobject/Collaboration/permission.t | 2 +- t/Asset/Wobject/Collaboration/unarchiveAll.t | 2 +- t/Asset/Wobject/Gallery/00base.t | 2 +- t/Asset/Wobject/GalleryAlbum/00base.t | 2 +- t/Asset/Wobject/GalleryAlbum/delete.t | 2 +- t/Asset/Wobject/GalleryAlbum/edit.t | 2 +- t/Asset/permissions.t | 10 +++++----- t/Group/resetGroupFields.t | 8 ++++---- t/lib/WebGUI/Test.pm | 4 ++-- 17 files changed, 41 insertions(+), 39 deletions(-) diff --git a/t/Asset/EMSSubmissionForm.t b/t/Asset/EMSSubmissionForm.t index 615d2fabc..12f92c226 100644 --- a/t/Asset/EMSSubmissionForm.t +++ b/t/Asset/EMSSubmissionForm.t @@ -354,7 +354,7 @@ is($approveSubmissions->run, 'done', 'approval done'); $sub1 = $sub1->cloneFromDb; is( $sub1->get('submissionStatus'),'created','approval successfull'); -my $ticket = WebGUI::Asset->newByDynamicClass($session, $sub1->get('ticketId')); +my $ticket = WebGUI::Asset->newById($session, $sub1->get('ticketId')); WebGUI::Test->assetsToPurge( $ticket ) if $ticket ; SKIP: { skip 'no ticket created', 1 unless isa_ok( $ticket, 'WebGUI::Asset::Sku::EMSTicket', 'approval created a ticket'); @@ -373,7 +373,7 @@ $cleanupSubmissions->reset; is($cleanupSubmissions->run, 'complete', 'cleanup complete'); is($cleanupSubmissions->run, 'done', 'cleanup done'); -$sub2 = WebGUI::Asset->newByDynamicClass($session, $sub2Id); +$sub2 = WebGUI::Asset->newById($session, $sub2Id); is( $sub2, undef, 'submission deleted'); } # end of workflow skip diff --git a/t/Asset/File/GalleryFile/Photo/edit.t b/t/Asset/File/GalleryFile/Photo/edit.t index 389320a9a..ff860d8ad 100644 --- a/t/Asset/File/GalleryFile/Photo/edit.t +++ b/t/Asset/File/GalleryFile/Photo/edit.t @@ -120,11 +120,11 @@ SKIP: { }; # Make sure properties were saved - my $photo = WebGUI::Asset->newByDynamicClass( $session, $album->getFileIds->[0] ); + my $photo = WebGUI::Asset->newById( $session, $album->getFileIds->[0] ); cmp_deeply( $photo->get, superhashof( $properties ), "Photo properties saved correctly" ); # First File in an album should update assetIdThumbnail - my $album = WebGUI::Asset->newByDynamicClass( $session, $album->getId ); + my $album = WebGUI::Asset->newById( $session, $album->getId ); is( $album->get('assetIdThumbnail'), $photo->getId, "Album assetIdThumbnail gets set by first File added", diff --git a/t/Asset/Post.t b/t/Asset/Post.t index ec495ae1a..6c1c2db10 100644 --- a/t/Asset/Post.t +++ b/t/Asset/Post.t @@ -84,6 +84,7 @@ my $post = $collab->addChild($props, @addArgs); $versionTag->commit(); WebGUI::Test->tagsToRollback($versionTag); +$post = $post->cloneFromDb; # Test for a sane object type isa_ok($post, 'WebGUI::Asset::Post::Thread'); @@ -120,7 +121,7 @@ $post->update({synopsis => $synopsis}); ##There is a bug in DBD::mysql with not properly encoding 8-bit characters. Also, HTML::Entities produces ##8-bit utf8 (not strict) characters. So we write a quick test to make sure our patch in splitTag works correctly. -my $dbPost = WebGUI::Asset->newByDynamicClass($session, $post->getId); +my $dbPost = WebGUI::Asset->newById($session, $post->getId); like($dbPost->get('synopsis'), qr/Brandhei.e Neuigkeiten rund um's Klettern f.r euch aus der Region /, 'patch test for DBD::Mysql and HTML::Entities'); ($synopsis, $content) = $post->getSynopsisAndContent('', q|less than < greater than >|); diff --git a/t/Asset/Post/Thread.t b/t/Asset/Post/Thread.t index b89ae98ec..06877053e 100644 --- a/t/Asset/Post/Thread.t +++ b/t/Asset/Post/Thread.t @@ -49,6 +49,8 @@ my $props = { my $thread = $collab->addChild($props, @addArgs); $versionTag->commit(); +$collab = $collab->cloneFromDb; +$thread = $thread->cloneFromDb; my $uncommittedThread = $collab->addChild($props, @addArgs); diff --git a/t/Asset/Post/Thread/getAdjacentThread.t b/t/Asset/Post/Thread/getAdjacentThread.t index 12b26890c..ed6d28cfd 100644 --- a/t/Asset/Post/Thread/getAdjacentThread.t +++ b/t/Asset/Post/Thread/getAdjacentThread.t @@ -61,6 +61,10 @@ my @threads = ( $_->setSkipNotification for @threads; $versionTags[-1]->commit; +WebGUI::Test->addToCleanup($versionTags[-1]); +foreach my $asset(@threads, $collab) { + $asset = $asset->cloneFromDb; +} #---------------------------------------------------------------------------- # Tests @@ -133,6 +137,7 @@ $collab->update({ sortOrder => 'desc', }); push @versionTags, WebGUI::VersionTag->getWorking( $session ); +WebGUI::Test->addToCleanup($versionTags[-1]); push @threads, $collab->addChild( { className => 'WebGUI::Asset::Post::Thread', title => "Abababa", @@ -146,12 +151,6 @@ testGetAdjacentThread( "sort by default from asset with version tag", $sort, [ q $session->scratch->delete($collab->getId.'_sortBy'); $session->scratch->delete($collab->getId.'_sortDir'); -#---------------------------------------------------------------------------- -# Cleanup -END { - $_->rollback for @versionTags; -} - #---------------------------------------------------------------------------- # testGetAdjacentThread ( label, sort, order, @threads ) # Performs two tests for each thread in [order] @@ -161,10 +160,10 @@ END { # @threads = all the threads sub testGetAdjacentThread { my ( $label, $sort, $order, @threads ) = @_; - + my $idxFirst = shift @{$order}; my $idxLast = pop @{$order}; - + # First is( $threads[$idxFirst]->getNextThread->getId, getNextThread( $sort, $threads[$idxFirst], @threads )->getId, @@ -220,7 +219,7 @@ sub sortThreads { sub getNextThread { my ( $sortSub, $thread, @threads ) = @_; my @sorted = @{ sortThreads( $sortSub, @threads ) }; - + for my $i ( 0..$#sorted ) { if ( $sorted[$i]->getId eq $thread->getId ) { return $sorted[$i+1]; @@ -232,7 +231,7 @@ sub getPreviousThread { my ( $sortSub, $thread, @threads ) = @_; # Use reverse so that $i-1 != -1 (which gets us the last thread) my @sorted = reverse @{ sortThreads( $sortSub, @threads ) }; - + for my $i ( 0..$#sorted ) { if ( $sorted[$i]->getId eq $thread->getId ) { return $sorted[$i+1]; diff --git a/t/Asset/Post/Thread/permission.t b/t/Asset/Post/Thread/permission.t index 240c58b65..103637024 100644 --- a/t/Asset/Post/Thread/permission.t +++ b/t/Asset/Post/Thread/permission.t @@ -62,8 +62,8 @@ my $thread $versionTag->commit( { timeout => 1_000_000 } ); # Re-load the collab to get the newly committed properties -$collab = WebGUI::Asset->newByDynamicClass( $session, $collab->getId ); -$thread = WebGUI::Asset->newByDynamicClass( $session, $thread->getId ); +$collab = WebGUI::Asset->newById( $session, $collab->getId ); +$thread = WebGUI::Asset->newById( $session, $thread->getId ); #---------------------------------------------------------------------------- # Tests @@ -104,7 +104,7 @@ $maker->prepare( { # Reply with allowReplies = 0 $collab->update({ allowReplies => 0 }); -$thread = WebGUI::Asset->newByDynamicClass( $session, $thread->getId ); +$thread = WebGUI::Asset->newById( $session, $thread->getId ); $maker->prepare( { object => $thread, method => 'canReply', diff --git a/t/Asset/Post/permission.t b/t/Asset/Post/permission.t index dcd0fd63b..21bc8e82e 100644 --- a/t/Asset/Post/permission.t +++ b/t/Asset/Post/permission.t @@ -67,9 +67,9 @@ my $post $versionTag->commit( { timeout => 1_000_000 } ); # Re-load the collab to get the newly committed properties -$collab = WebGUI::Asset->newByDynamicClass( $session, $collab->getId ); -$thread = WebGUI::Asset->newByDynamicClass( $session, $thread->getId ); -$post = WebGUI::Asset->newByDynamicClass( $session, $post->getId ); +$collab = WebGUI::Asset->newById( $session, $collab->getId ); +$thread = WebGUI::Asset->newById( $session, $thread->getId ); +$post = WebGUI::Asset->newById( $session, $post->getId ); #---------------------------------------------------------------------------- # Tests diff --git a/t/Asset/Sku/ProductCollateral.t b/t/Asset/Sku/ProductCollateral.t index 5ed86a964..db5a95270 100644 --- a/t/Asset/Sku/ProductCollateral.t +++ b/t/Asset/Sku/ProductCollateral.t @@ -302,7 +302,7 @@ my $product6 = $root->addChild({ $newVid = $product6->setCollateral('variantsJSON', 'vid', 'new', { wideChar => qq!on 16\x{201d} hand-crocheted Cord! , vid => 'new' }); -my $product6a = WebGUI::Asset->newByDynamicClass($session, $product6->getId); +my $product6a = WebGUI::Asset->newById($session, $product6->getId); lives_ok { $product6a->getAllCollateral('variantsJSON', 'vid', $newVid); }, 'Product collateral handles wide-character encodings okay'; $product6->purge; diff --git a/t/Asset/Wobject/Collaboration/permission.t b/t/Asset/Wobject/Collaboration/permission.t index 87f24ea98..07b3fba3e 100644 --- a/t/Asset/Wobject/Collaboration/permission.t +++ b/t/Asset/Wobject/Collaboration/permission.t @@ -51,7 +51,7 @@ my $collab $versionTag->commit( { timeout => 1_000_000 } ); # Re-load the collab to get the newly committed properties -$collab = WebGUI::Asset->newByDynamicClass( $session, $collab->getId ); +$collab = WebGUI::Asset->newById( $session, $collab->getId ); #---------------------------------------------------------------------------- # Tests diff --git a/t/Asset/Wobject/Collaboration/unarchiveAll.t b/t/Asset/Wobject/Collaboration/unarchiveAll.t index cb3866b07..b06242152 100644 --- a/t/Asset/Wobject/Collaboration/unarchiveAll.t +++ b/t/Asset/Wobject/Collaboration/unarchiveAll.t @@ -50,7 +50,7 @@ plan tests => 1; # Increment this number for each test you create #---------------------------------------------------------------------------- # www_unarchiveAll sets all threads to approved $collab->www_unarchiveAll; -$threads[0] = WebGUI::Asset->newByDynamicClass( $session, $threads[0]->getId ); +$threads[0] = WebGUI::Asset->newById( $session, $threads[0]->getId ); is( $threads[0]->get('status'), 'approved', "unarchiveAll sets thread to approved" ); #vim:ft=perl diff --git a/t/Asset/Wobject/Gallery/00base.t b/t/Asset/Wobject/Gallery/00base.t index 615bc9c1c..bdce13580 100644 --- a/t/Asset/Wobject/Gallery/00base.t +++ b/t/Asset/Wobject/Gallery/00base.t @@ -62,7 +62,7 @@ my $properties = $gallery->get; $gallery->purge; is( - WebGUI::Asset->newByDynamicClass($session, $properties->{assetId}), undef, + WebGUI::Asset->newById($session, $properties->{assetId}), undef, "Gallery no longer able to be instanciated", ); diff --git a/t/Asset/Wobject/GalleryAlbum/00base.t b/t/Asset/Wobject/GalleryAlbum/00base.t index 9de44c814..8414f54d5 100644 --- a/t/Asset/Wobject/GalleryAlbum/00base.t +++ b/t/Asset/Wobject/GalleryAlbum/00base.t @@ -67,7 +67,7 @@ my $properties = $album->get; $album->purge; is( - WebGUI::Asset->newByDynamicClass($session, $properties->{assetId}), undef, + WebGUI::Asset->newById($session, $properties->{assetId}), undef, "Album no longer able to be instanciated", ); diff --git a/t/Asset/Wobject/GalleryAlbum/delete.t b/t/Asset/Wobject/GalleryAlbum/delete.t index a590a81e4..bd58e20bf 100644 --- a/t/Asset/Wobject/GalleryAlbum/delete.t +++ b/t/Asset/Wobject/GalleryAlbum/delete.t @@ -96,7 +96,7 @@ $maker->prepare({ $maker->run; is( - WebGUI::Asset->newByDynamicClass( $session, $assetId ), + WebGUI::Asset->newById( $session, $assetId ), undef, "GalleryAlbum cannot be instanciated after www_deleteConfirm", ); diff --git a/t/Asset/Wobject/GalleryAlbum/edit.t b/t/Asset/Wobject/GalleryAlbum/edit.t index b250ac53a..478fb43de 100644 --- a/t/Asset/Wobject/GalleryAlbum/edit.t +++ b/t/Asset/Wobject/GalleryAlbum/edit.t @@ -109,7 +109,7 @@ $mech->content_contains( ); # Creates the album with the appropriate properties -my $album = WebGUI::Asset->newByDynamicClass( $session, $gallery->getAlbumIds->[0] ); +my $album = WebGUI::Asset->newById( $session, $gallery->getAlbumIds->[0] ); cmp_deeply( $properties, subhashof( $album->get ), "Properties from edit form are set correctly" ); #---------------------------------------------------------------------------- diff --git a/t/Asset/permissions.t b/t/Asset/permissions.t index f81c2967e..e2972ef42 100644 --- a/t/Asset/permissions.t +++ b/t/Asset/permissions.t @@ -622,14 +622,14 @@ TODO: { ################################################################ # -# newByDynamicClass +# newById # ################################################################ -my $newFixTitleAsset = WebGUI::Asset->newByDynamicClass($session, $fixTitleAsset->getId); -isnt($newFixTitleAsset, undef, 'newByDynamicClass did not fail'); -isa_ok($newFixTitleAsset, 'WebGUI::Asset', 'newByDynamicClass: able to look up an existing asset by id'); -cmp_deeply($newFixTitleAsset->{_properties}, $fixTitleAsset->{_properties}, 'newByDynamicClass created a duplicate asset'); +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'); ################################################################ # diff --git a/t/Group/resetGroupFields.t b/t/Group/resetGroupFields.t index 58e7cb560..98adb58ac 100644 --- a/t/Group/resetGroupFields.t +++ b/t/Group/resetGroupFields.t @@ -107,7 +107,7 @@ is($userActivity->get('groupId'), $activityGroup->getId, 'group in Workflow Acti $assetGroup->delete; -my $newSnippet1 = WebGUI::Asset->newByDynamicClass($session, $snippet1->getId); +my $newSnippet1 = WebGUI::Asset->newById($session, $snippet1->getId); cmp_deeply( $newSnippet1->get, @@ -118,7 +118,7 @@ cmp_deeply( 'groupIdEdit updated on test snippet' ); -my $newSnippet2 = WebGUI::Asset->newByDynamicClass($session, $snippet2->getId); +my $newSnippet2 = WebGUI::Asset->newById($session, $snippet2->getId); cmp_deeply( $newSnippet2->get, @@ -129,7 +129,7 @@ cmp_deeply( 'other snippet not touched' ); -my $newSnippet3 = WebGUI::Asset->newByDynamicClass($session, $snippet3->getId); +my $newSnippet3 = WebGUI::Asset->newById($session, $snippet3->getId); cmp_deeply( $newSnippet3->get, @@ -140,7 +140,7 @@ cmp_deeply( 'multiple fields updated' ); -my $newGallery1 = WebGUI::Asset->newByDynamicClass($session, $gallery1->getId); +my $newGallery1 = WebGUI::Asset->newById($session, $gallery1->getId); cmp_deeply( $newGallery1->get, diff --git a/t/lib/WebGUI/Test.pm b/t/lib/WebGUI/Test.pm index 16fdc2c2a..86898059c 100644 --- a/t/lib/WebGUI/Test.pm +++ b/t/lib/WebGUI/Test.pm @@ -247,13 +247,13 @@ sub _mockAssetInits { # } # goto $original_new; # }; - my $original_newByDynamicClass = \&WebGUI::Asset::newById; + my $original_newById = \&WebGUI::Asset::newById; *WebGUI::Asset::newById = sub { my ($class, $session, $assetId, $revisionDate) = @_; if ($mockedAssetIds{$assetId}) { return $mockedAssetIds{$assetId}; } - goto $original_newByDynamicClass; + goto $original_newById; }; my $original_newPending = \&WebGUI::Asset::newPending; *WebGUI::Asset::newPending = sub { From d690148c2cf3c51a5579c46476f8b59179f576a4 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 21:03:27 -0700 Subject: [PATCH 038/101] Fix a syntax error in the SQL to get shortcuts in the trash. --- lib/WebGUI/AssetTrash.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/WebGUI/AssetTrash.pm b/lib/WebGUI/AssetTrash.pm index 5e5ff1297..e954a4445 100644 --- a/lib/WebGUI/AssetTrash.pm +++ b/lib/WebGUI/AssetTrash.pm @@ -64,7 +64,7 @@ sub getAssetsInTrash { my $sth = $self->session->db->read(" select asset.assetId, - assetData.revisionDate, + assetData.revisionDate from asset left join From 01ba8203c8d6a193f2ca864c8ce36238ba369008 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 21:05:53 -0700 Subject: [PATCH 039/101] Update test for exception handling --- t/Asset/Shortcut/010-linked-asset.t | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/t/Asset/Shortcut/010-linked-asset.t b/t/Asset/Shortcut/010-linked-asset.t index ab3eec740..e448d3691 100644 --- a/t/Asset/Shortcut/010-linked-asset.t +++ b/t/Asset/Shortcut/010-linked-asset.t @@ -108,7 +108,7 @@ eval { }; is( - $contentLastModified, 0, + $contentLastModified, undef, "Purged Linked Asset: getContentLastModified returns 0 when linked asset missing", ); @@ -122,10 +122,10 @@ init(); $snippet->trash(); $snippet->purge(); -$shortcut = $shortcut->cloneFromDb(); +$shortcut = eval { $shortcut->cloneFromDb(); }; ok( - !defined $shortcut, + Exception::Class->caught(), "Purge Linked Asset: Shortcut is purged even though it's in the trash" ); @@ -135,10 +135,10 @@ init(); #---------------------------------------------------------------------------- # Test purging snippet purges shortcut also $snippet->purge; -$shortcut = $shortcut->cloneFromDb(); +$shortcut = eval { $shortcut->cloneFromDb(); }; ok( - !defined $shortcut, + Exception::Class->caught(), "Purge Linked Asset: Shortcut is not defined", ); From f3c1c0e4a5265f9b372c01ff38d8d92323b70fa9 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 21:10:44 -0700 Subject: [PATCH 040/101] Better handling of calling validParent without an asset, somewhere. --- lib/WebGUI/AssetLineage.pm | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/WebGUI/AssetLineage.pm b/lib/WebGUI/AssetLineage.pm index 95840cc12..acc78da01 100644 --- a/lib/WebGUI/AssetLineage.pm +++ b/lib/WebGUI/AssetLineage.pm @@ -999,6 +999,7 @@ sub validParent { my $class = shift; my $session = shift; my $asset = shift || $session->asset; + return 0 unless $asset; my $parent_classes = $class->valid_parent_classes; foreach my $parentClass (@{ $class->valid_parent_classes}) { return 1 if $asset->isa($parentClass); From e69a26db8c4183d4f0fda507d133cc308444b540 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 13 May 2010 21:14:07 -0700 Subject: [PATCH 041/101] Update test to remove use_ok, SKIP. --- t/Asset/Story.t | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/t/Asset/Story.t b/t/Asset/Story.t index 6cfecce5a..54eaaddab 100644 --- a/t/Asset/Story.t +++ b/t/Asset/Story.t @@ -18,6 +18,7 @@ use WebGUI::Session; use WebGUI::Storage; use WebGUI::User; use WebGUI::Group; +use WebGUI::Asset::Story; use Test::More; # increment this value for each test you create use Test::Deep; @@ -82,18 +83,10 @@ WebGUI::Test->storagesToDelete($storage1, $storage2); ############################################################ my $tests = 45; -plan tests => 1 - + $tests +plan tests => $tests + $canEditMaker->plan ; -my $class = 'WebGUI::Asset::Story'; -my $loaded = use_ok($class); - -SKIP: { - -skip "Unable to load module $class", $tests unless $loaded; - ############################################################ # # validParent @@ -439,7 +432,5 @@ cmp_bag( '...asset package data has the storage locations in it' ); -} - END { } From 4056d7019eadafa654d92e8b0ff9b16ba70d9544 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 16 May 2010 20:31:07 -0700 Subject: [PATCH 042/101] Drop tests for putting an Article below a calendar. This is now permitted. --- t/Asset/Wobject/Calendar.t | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/t/Asset/Wobject/Calendar.t b/t/Asset/Wobject/Calendar.t index 0497a2260..8604798cd 100644 --- a/t/Asset/Wobject/Calendar.t +++ b/t/Asset/Wobject/Calendar.t @@ -57,7 +57,7 @@ use Data::Dumper; use WebGUI::Asset::Wobject::Calendar; use WebGUI::Asset::Event; -plan tests => 14 + scalar @icalWrapTests; +plan tests => 12 + scalar @icalWrapTests; my $session = WebGUI::Test->session; @@ -82,10 +82,6 @@ isa_ok($cal, 'WebGUI::Asset::Wobject::Calendar'); my $event = $cal->addChild({className=>'WebGUI::Asset::Event'}); isa_ok($event, 'WebGUI::Asset::Event','Can add Events as a child to the calendar.'); -my $article = $cal->addChild({className=>"WebGUI::Asset::Wobject::Article"}); -isnt(ref $article, 'WebGUI::Asset::Wobject::Article', "Can't add an article as a child to the calendar."); -ok(! defined $article, '... addChild returned undef'); - my $dt = WebGUI::DateTime->new($session, mysql => '2001-08-16 8:00:00', time_zone => 'America/Chicago'); my $vars = {}; From 757eb8d9fa6e80594895f47e43e5a40873e8e9fd Mon Sep 17 00:00:00 2001 From: Scott Walters Date: Wed, 19 May 2010 07:52:43 -0400 Subject: [PATCH 043/101] PID files contain the PID so that on next run, we can test to see if that PID is still alive. If it isn't, the daemon was kill -9'd, the system crashed, or similar. It isn't running any more and it's safe to start up again. Don't die on startup unless the PID in the PID file is valid. --- sbin/spectre.pl | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/sbin/spectre.pl b/sbin/spectre.pl index d1991ae9e..13bbd8954 100755 --- a/sbin/spectre.pl +++ b/sbin/spectre.pl @@ -105,8 +105,20 @@ elsif ($daemon) { die "Spectre is already running.\n"; } elsif (-e $pidFileName){ - die "pidFile $pidFileName already exists\n"; + # oh, ffs ... die "pidFile $pidFileName already exists\n"; + open my $pidFile, '<', $pidFileName or die "$pidFileName: $!"; + (my $pid) = readline $pidFile; + chomp $pid; + if(defined $pid and $pid =~ m/^(\d+)$/) { + if(kill 0, $1) { + die "$0: already running as PID $1"; + } else { + warn "pidfile contains $pid but that process seems to have terminated" + } + } + close $pidFile; } + # XXXX warn if we can't open the log file before forking or else make it not fatal or else close STDOUT/STDERR afterwards; don't fail silently -- sdw #fork and exit(sleep(1) and print((ping())?"Spectre failed to start!\n":"Spectre started successfully!\n")); #Can't have right now. require POSIX; fork and exit; From aeb36106e241325a1c06238b0c62611aa9ba8eea Mon Sep 17 00:00:00 2001 From: Scott Walters Date: Wed, 19 May 2010 12:57:01 -0400 Subject: [PATCH 044/101] warning / Useless use of /d modifier in transliteration operator --- lib/WebGUI/Form/Zipcode.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/WebGUI/Form/Zipcode.pm b/lib/WebGUI/Form/Zipcode.pm index 75e15561d..9d71ad137 100644 --- a/lib/WebGUI/Form/Zipcode.pm +++ b/lib/WebGUI/Form/Zipcode.pm @@ -94,7 +94,7 @@ sub getValue { my $self = shift; my $value = $self->SUPER::getValue(@_); $value =~ tr/\r\n//d; - $value =~ tr/a-z/A-Z/d; + $value =~ tr/a-z/A-Z/; if ($value =~ /^[A-Z\d\s\-]+$/) { return $value; } From 2d722c3477a9ed98ff23a2c5bf08aae5f94b1bf7 Mon Sep 17 00:00:00 2001 From: Scott Walters Date: Wed, 19 May 2010 13:00:34 -0400 Subject: [PATCH 045/101] 8.x additional module deps --- sbin/testEnvironment.pl | 1 + 1 file changed, 1 insertion(+) diff --git a/sbin/testEnvironment.pl b/sbin/testEnvironment.pl index ad7a1edd7..5bf279540 100755 --- a/sbin/testEnvironment.pl +++ b/sbin/testEnvironment.pl @@ -139,6 +139,7 @@ checkModule("JavaScript::Minifier::XS", "0.05" ); checkModule("Readonly", "1.03" ); checkModule("Moose", "0.93" ); checkModule("MooseX::Storage", "0.23" ); +checkModule("MooseX::Storage::Format::JSON","0.27" ); checkModule("namespace::autoclean", "0.09" ); checkModule("Business::PayPal::API", "0.62" ); checkModule("Locales", "0.10" ); From 9e50f5e8c235fa3838cf4ce99090e8cae4ee4647 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 20 May 2010 15:45:28 -0700 Subject: [PATCH 046/101] 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 047/101] 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 048/101] 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 049/101] 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 050/101] 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 051/101] 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 052/101] 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 053/101] 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 054/101] 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 055/101] 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 056/101] 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 057/101] 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 058/101] 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 059/101] 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 060/101] 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 061/101] 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 062/101] 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 063/101] 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 064/101] 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 065/101] 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 066/101] 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 067/101] 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; - } } From 89302e9875a4ada89287ab9f154c8e71a6696fe4 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 23 May 2010 16:33:30 -0700 Subject: [PATCH 068/101] Fix taxConfiguration property for the Sku asset. --- lib/WebGUI/Asset/Sku.pm | 2 +- t/Asset/Sku.t | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/WebGUI/Asset/Sku.pm b/lib/WebGUI/Asset/Sku.pm index d9f16f7d5..0bff8a03a 100644 --- a/lib/WebGUI/Asset/Sku.pm +++ b/lib/WebGUI/Asset/Sku.pm @@ -59,7 +59,7 @@ property vendorId => ( property taxConfiguration => ( noFormPost => 1, fieldType => 'hidden', - defaultValue => '{}', + default => '{}', ); property shipsSeparately => ( tab => 'shop', diff --git a/t/Asset/Sku.t b/t/Asset/Sku.t index 9d67cddb1..8a906c1c2 100644 --- a/t/Asset/Sku.t +++ b/t/Asset/Sku.t @@ -30,20 +30,21 @@ my $session = WebGUI::Test->session; #---------------------------------------------------------------------------- # Tests -plan tests => 22; # Increment this number for each test you create +plan tests => 23; # Increment this number for each test you create #---------------------------------------------------------------------------- # put your tests here my $root = WebGUI::Asset->getRoot($session); -warn "Make sku\n"; +note "Make sku\n"; my $sku = $root->addChild({ className=>"WebGUI::Asset::Sku", title=>"Test Sku", }); isa_ok($sku, "WebGUI::Asset::Sku"); -addToCleanup($sku); +WebGUI::Test->addToCleanup($sku); $sku->addToCart; +WebGUI::Test->addToCleanup($sku->getCart); $sku->applyOptions({ test1 => "YY" @@ -53,6 +54,7 @@ my $options = $sku->getOptions; is($options->{test1}, "YY", "Can set and get an option."); +is $sku->taxConfiguration, '{}', 'default tax configuration is a string with an empty hashref in it'; is($sku->getMaxAllowedInCart, 99999999, "Got a valid default max in cart."); is($sku->getQuantityAvailable, 99999999, "skus should have an unlimited quantity by default"); is($sku->getQuantityAvailable, $sku->getMaxAllowedInCart, "quantity available and max allowed in cart should be the same"); @@ -81,7 +83,7 @@ ok(! $sku->isShippingRequired, 'Making sure that GLOB is no longer in effect'); isa_ok($sku->getCart, "WebGUI::Shop::Cart", "can get a cart object"); my $item = $sku->addToCart; isa_ok($item, "WebGUI::Shop::CartItem", "can add to cart"); -$item->cart->delete; my $loadSku = WebGUI::Asset::Sku->newBySku($session, $sku->get("sku")); is($loadSku->getId, $sku->getId, "newBySku() works."); + From d3d0e0336847ef78a8dbb3c5810f5992f6fbd5a1 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 23 May 2010 16:35:10 -0700 Subject: [PATCH 069/101] Remove some unneeded declared variables. --- t/Shop/TaxDriver/Generic.t | 1 - 1 file changed, 1 deletion(-) diff --git a/t/Shop/TaxDriver/Generic.t b/t/Shop/TaxDriver/Generic.t index 2aec479c6..d0f3ee923 100644 --- a/t/Shop/TaxDriver/Generic.t +++ b/t/Shop/TaxDriver/Generic.t @@ -45,7 +45,6 @@ plan tests => 78 my $storage; -my ($taxableDonation, $taxFreeDonation); ####################################################################### # From e4445a2e2b3aa3605c85dc817decda8195655d98 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Sun, 23 May 2010 17:58:50 -0700 Subject: [PATCH 070/101] Need an asset in order to check canAdd --- t/Asset/permissions.t | 1 + 1 file changed, 1 insertion(+) diff --git a/t/Asset/permissions.t b/t/Asset/permissions.t index 8add65c2c..a16f54eeb 100644 --- a/t/Asset/permissions.t +++ b/t/Asset/permissions.t @@ -163,6 +163,7 @@ plan tests => $canAddMaker->plan $session->config->set('assets/WebGUI::Asset/addGroup', $testGroups{'canAdd asset'}->getId ); +$session->asset(WebGUI::Asset->getDefault($session)); $canAddMaker->run; #Without proper group setup, Turn On Admin is excluded from adding assets via assetAddPrivilege From e924f9d3dfad338c31dcdd33ed409a51cfe34ac4 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Wed, 26 May 2010 15:57:51 -0700 Subject: [PATCH 071/101] Dump the dumping. --- t/Asset/Wobject/Search.t | 1 - 1 file changed, 1 deletion(-) diff --git a/t/Asset/Wobject/Search.t b/t/Asset/Wobject/Search.t index 978d01e0c..64b290435 100644 --- a/t/Asset/Wobject/Search.t +++ b/t/Asset/Wobject/Search.t @@ -123,7 +123,6 @@ $search->update({ $search->update({useContainers => 1}); $search->view; like $templateVars->{result_set}->[0]->{url}, qr{\?pn=\d}, 'search returns paginated URL for a Thread when useContainers=1'; - note Dumper $templateVars; WebGUI::Test->unmockAssetId($templateId); $session->request->setup_body({}); From 2c780536e873d93990b468c726615146663797ad Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 27 May 2010 15:30:42 -0700 Subject: [PATCH 072/101] Remove isa check since the class names are not predictable. --- t/Definition/Asset.t | 6 ------ 1 file changed, 6 deletions(-) diff --git a/t/Definition/Asset.t b/t/Definition/Asset.t index bdefc9671..1f96a843b 100644 --- a/t/Definition/Asset.t +++ b/t/Definition/Asset.t @@ -108,12 +108,6 @@ use WebGUI::Test; '->meta->get_property_list returns properties as a list in insertion order' ); - ::cmp_deeply( - [ $object->meta->get_all_properties ], - ::array_each(::isa('WebGUI::Definition::Meta::Property::Asset')), - '->meta->get_all_properties returns a list of Properties' - ); - ::cmp_deeply( [$object->getProperties ], [qw/property2 property1/], From 57fe0721ab6049e02c421cf2b1cb387f4eed42da Mon Sep 17 00:00:00 2001 From: Scott Walters Date: Thu, 27 May 2010 22:26:37 -0400 Subject: [PATCH 073/101] Calls to set() and update() set attributes as well as "properties". Fixes t/Keywords.t number 11. --- lib/WebGUI/AssetVersioning.pm | 3 ++- lib/WebGUI/Definition/Role/Object.pm | 23 +++++++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/lib/WebGUI/AssetVersioning.pm b/lib/WebGUI/AssetVersioning.pm index eeefe9f3b..ed2ebf409 100644 --- a/lib/WebGUI/AssetVersioning.pm +++ b/lib/WebGUI/AssetVersioning.pm @@ -126,7 +126,8 @@ sub addRevision { $session->db->commit; # current values, and the user set properties - my %mergedProperties = (%{$self->get}, %{$properties}, (status => 'pending', revisedBy => $session->user->userId, tagId => $workingTag->getId), ); + # my %mergedProperties = (%{$self->get}, %{$properties}, (status => 'pending', revisedBy => $session->user->userId, tagId => $workingTag->getId), ); # XXX results in the setting of read-only properties and nothing else seems to be done with this other than just set them again + my %mergedProperties = ( %{$properties}, status => 'pending', revisedBy => $session->user->userId, tagId => $workingTag->getId, ); #Instantiate new revision and fill with real data my $newVersion = WebGUI::Asset->newById($session, $self->getId, $now); diff --git a/lib/WebGUI/Definition/Role/Object.pm b/lib/WebGUI/Definition/Role/Object.pm index 4c1c74a79..e00358d4d 100644 --- a/lib/WebGUI/Definition/Role/Object.pm +++ b/lib/WebGUI/Definition/Role/Object.pm @@ -85,13 +85,23 @@ is not an attribute of the object, then it is silently ignored. =cut sub set { + my $self = shift; my $properties = @_ % 2 ? shift : { @_ }; - my @orderedProperties = $self->getProperties; - KEY: for my $property ( @orderedProperties ) { - next KEY unless exists $properties->{$property}; - $self->$property($properties->{$property}); + my %seen; + + my @settable = grep { ! $seen{$_}++ } ( + $self->getProperties, # $self->meta->get_all_property_list, # same as $self->getProperties + $self->getReadableAttributes, + ); + + for my $attribute ( @settable ) { + next unless exists $properties->{$attribute}; + $self->$attribute( $properties->{$attribute} ); } + + # ignore unknown properties + return 1; } @@ -181,5 +191,10 @@ sub getProperties { return $self->meta->get_all_property_list; } +sub getReadableAttributes { + my $self = shift; + return map $_->name, grep $_->has_accessor || $_->has_writer, $self->meta->get_all_attributes; +} + 1; From 0ae488290646e4a35b5b75f4edd17870bc583196 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 27 May 2010 20:54:14 -0700 Subject: [PATCH 074/101] Give tests prefixes so they run in a predictable order. --- t/tests/Test/WebGUI/Asset.pm | 247 +++++++++++++++++++---------------- 1 file changed, 131 insertions(+), 116 deletions(-) diff --git a/t/tests/Test/WebGUI/Asset.pm b/t/tests/Test/WebGUI/Asset.pm index 67b840186..d72f49a56 100644 --- a/t/tests/Test/WebGUI/Asset.pm +++ b/t/tests/Test/WebGUI/Asset.pm @@ -78,7 +78,93 @@ sub _constructor : Test(4) { } -sub title : Test(6) { +sub t_00_class_dispatch : Test(2) { + my $test = shift; + my $session = $test->session; + note "Class dispatch"; + my $asset = $test->class->new({session => $session}); + + my $asset = WebGUI::Asset->new({ + session => $session, + title => 'testing snippet', + className => 'WebGUI::Asset::Snippet', + }); + + isa_ok $asset, 'WebGUI::Asset'; + is $asset->className, 'WebGUI::Asset', 'passing className is ignored'; +} + +sub t_00_get_tables : Test(1) { + my $test = shift; + note "get_tables"; + my @tables = $test->class->meta->get_tables; + cmp_bag( + \@tables, + $test->list_of_tables, + 'Set of tables for properties is correct' + ); +} + +sub t_00_getParent : Test(2) { + my $test = shift; + my $session = $test->session; + note "getParent"; + my $testId1 = 'wg8TestAsset0000000001'; + my $testId2 = 'wg8TestAsset0000000002'; + my $now = time(); + my $baseLineage = $session->db->quickScalar('select lineage from asset where assetId=?',['PBasset000000000000002']); + my $testLineage = $baseLineage. '909090'; + $session->db->write("insert into asset (assetId, className, lineage) VALUES (?,?,?)", [$testId1, 'WebGUI::Asset', $testLineage]); + $session->db->write("insert into assetData (assetId, revisionDate, status) VALUES (?,?,?)", [$testId1, $now, 'approved']); + my $testLineage2 = $testLineage . '000001'; + $session->db->write("insert into asset (assetId, className, parentId, lineage) VALUES (?,?,?,?)", [$testId2, 'WebGUI::Asset', $testId1, $testLineage2]); + $session->db->write("insert into assetData (assetId, revisionDate) VALUES (?,?)", [$testId2, $now]); + + my $testAsset = WebGUI::Asset->new($session, $testId2, $now); + is $testAsset->parentId, $testId1, 'parentId assigned correctly on db fetch in new'; + my $testParent = $testAsset->getParent(); + isa_ok $testParent, 'WebGUI::Asset'; + + $session->db->write("delete from asset where assetId like 'wg8TestAsset00000%'"); + $session->db->write("delete from assetData where assetId like 'wg8TestAsset00000%'"); +} + +sub t_00_newByPropertyHashRef : Test(2) { + my $test = shift; + my $session = $test->session; + note "newByPropertyHashRef"; + my $asset; + $asset = WebGUI::Asset->newByPropertyHashRef($session, {className => $test->class, title => 'The Shawshank Snippet'}); + isa_ok $asset, $test->class; + is $asset->title, 'The Shawshank Snippet', 'title is assigned from the property hash'; +} + +sub t_00_scan_properties : Test(1) { + note "scan properties for table definitions"; + my $test = shift; + my @properties = $test->class->meta->get_all_properties; + my @undefined_tables = (); + foreach my $prop (@properties) { + push @undefined_tables, $prop->name if (!$prop->tableName); + } + ok !@undefined_tables, "all properties have tables defined" + or diag "except these: ".join ", ", @undefined_tables; +} + +sub t_01_assetId : Test(4) { + my $test = shift; + my $session = $test->session; + my $asset = $test->class->new({session => $session}); + note "assetId, getId"; + can_ok $asset, qw/assetId getId/; + ok $session->id->valid( $asset->assetId), 'assetId generated by default is valid'; + is $asset->assetId, $asset->getId, '... getId is an alias for assetId'; + + $asset = $test->class->new({ session => $session, assetId => '' }); + ok !$session->id->valid($asset->assetId), 'blank assetId in constructor is okay??'; +} + +sub t_01_title : Test(6) { my $test = shift; my $session = $test->session; my $asset = $test->class->new({session => $session}); @@ -100,7 +186,7 @@ sub title : Test(6) { } -sub menuTitle : Test(8) { +sub t_01_menuTitle : Test(8) { my $test = shift; my $session = $test->session; my $asset = $test->class->new({session => $session}); @@ -136,36 +222,7 @@ sub menuTitle : Test(8) { is $asset->menuTitle, 'menuTitle asset', '... set via constructor'; } -sub assetId : Test(4) { - my $test = shift; - my $session = $test->session; - my $asset = $test->class->new({session => $session}); - note "assetId, getId"; - can_ok $asset, qw/assetId getId/; - ok $session->id->valid( $asset->assetId), 'assetId generated by default is valid'; - is $asset->assetId, $asset->getId, '... getId is an alias for assetId'; - - $asset = $test->class->new({ session => $session, assetId => '' }); - ok !$session->id->valid($asset->assetId), 'blank assetId in constructor is okay??'; -} - -sub class_dispatch : Test(2) { - my $test = shift; - my $session = $test->session; - note "Class dispatch"; - my $asset = $test->class->new({session => $session}); - - my $asset = WebGUI::Asset->new({ - session => $session, - title => 'testing snippet', - className => 'WebGUI::Asset::Snippet', - }); - - isa_ok $asset, 'WebGUI::Asset'; - is $asset->className, 'WebGUI::Asset', 'passing className is ignored'; -} - -sub uiLevel : Test(1) { +sub t_01_uiLevel : Test(1) { my $test = shift; my $session = $test->session; note "uiLevel"; @@ -173,7 +230,7 @@ sub uiLevel : Test(1) { is $asset->uiLevel, $test->assetUiLevel, 'asset uiLevel check'; } -sub write_update : Test(8) { +sub t_01_write_update : Test(8) { my $test = shift; my $session = $test->session; note "write, update"; @@ -210,89 +267,7 @@ sub write_update : Test(8) { $session->db->write("delete from assetData where assetId=?", [$testId]); } -sub keywords : Test(3) { - my $test = shift; - my $session = $test->session; - my ($tag, $asset, @parents) = $test->getAnchoredAsset(); - can_ok $asset, 'keywords'; - $asset->keywords('chess set'); - is $asset->keywords, 'chess set', 'set and get of keywords via direct accessor'; - is $asset->get('keywords'), 'chess set', 'via get method'; -} - -sub get_tables : Test(1) { - my $test = shift; - note "get_tables"; - my @tables = $test->class->meta->get_tables; - cmp_bag( - \@tables, - $test->list_of_tables, - 'Set of tables for properties is correct' - ); -} - -sub getParent : Test(2) { - my $test = shift; - my $session = $test->session; - note "getParent"; - my $testId1 = 'wg8TestAsset0000000001'; - my $testId2 = 'wg8TestAsset0000000002'; - my $now = time(); - my $baseLineage = $session->db->quickScalar('select lineage from asset where assetId=?',['PBasset000000000000002']); - my $testLineage = $baseLineage. '909090'; - $session->db->write("insert into asset (assetId, className, lineage) VALUES (?,?,?)", [$testId1, 'WebGUI::Asset', $testLineage]); - $session->db->write("insert into assetData (assetId, revisionDate, status) VALUES (?,?,?)", [$testId1, $now, 'approved']); - my $testLineage2 = $testLineage . '000001'; - $session->db->write("insert into asset (assetId, className, parentId, lineage) VALUES (?,?,?,?)", [$testId2, 'WebGUI::Asset', $testId1, $testLineage2]); - $session->db->write("insert into assetData (assetId, revisionDate) VALUES (?,?)", [$testId2, $now]); - - my $testAsset = WebGUI::Asset->new($session, $testId2, $now); - is $testAsset->parentId, $testId1, 'parentId assigned correctly on db fetch in new'; - my $testParent = $testAsset->getParent(); - isa_ok $testParent, 'WebGUI::Asset'; - - $session->db->write("delete from asset where assetId like 'wg8TestAsset00000%'"); - $session->db->write("delete from assetData where assetId like 'wg8TestAsset00000%'"); -} - -sub newByPropertyHashRef : Test(2) { - my $test = shift; - my $session = $test->session; - note "newByPropertyHashRef"; - my $asset; - $asset = WebGUI::Asset->newByPropertyHashRef($session, {className => $test->class, title => 'The Shawshank Snippet'}); - isa_ok $asset, $test->class; - is $asset->title, 'The Shawshank Snippet', 'title is assigned from the property hash'; -} - -sub scan_properties : Test(1) { - note "scan properties for table definitions"; - my $test = shift; - my @properties = $test->class->meta->get_all_properties; - my @undefined_tables = (); - foreach my $prop (@properties) { - push @undefined_tables, $prop->name if (!$prop->tableName); - } - ok !@undefined_tables, "all properties have tables defined" - or diag "except these: ".join ", ", @undefined_tables; -} - -sub purge : Test(3) { - note "purge"; - my $test = shift; - my $session = $test->session; - my ($tag, $asset, @parents) = $test->getAnchoredAsset(); - my @tables = $asset->meta->get_tables; - ok $asset->purge, 'purge returns true if it was purged'; - throws_ok { WebGUI::Asset->newById($session, $asset->assetId); } 'WebGUI::Error::InvalidParam', 'Unable to fetch asset by assetId now'; - my $exists_in_table = 0; - foreach my $table (@tables) { - $exists_in_table ||= $session->db->quickScalar("select count(*) from `$table` where assetId=?",[$asset->assetId]); - } - ok ! $exists_in_table, 'assetId removed from all asset tables'; -} - -sub cut_paste : Test(5) { +sub t_03_addRevision : Test(5) { note "cut"; my $test = shift; my $session = $test->session; @@ -308,6 +283,46 @@ sub cut_paste : Test(5) { $session->asset($session_asset); } +sub t_05_cut_paste : Test(5) { + note "cut"; + my $test = shift; + my $session = $test->session; + my ($tag, $asset, @parents) = $test->getAnchoredAsset(); + ok $asset->cut, 'cut returns true if it was cut'; + is $asset->state, 'clipboard', 'asset state updated'; + my $session_asset = $session->asset(); + $session->asset($parents[-1]); + ok $asset->canPaste, 'canPaste: allowed to paste here'; + ok $parents[-1]->paste($asset->assetId), 'paste returns true when it pastes'; + $asset_prime = $asset->cloneFromDb; + is $asset_prime->state, 'published', 'asset state updated'; + $session->asset($session_asset); +} + +sub t_05_keywords : Test(3) { + my $test = shift; + my $session = $test->session; + my ($tag, $asset, @parents) = $test->getAnchoredAsset(); + can_ok $asset, 'keywords'; + $asset->keywords('chess set'); + is $asset->keywords, 'chess set', 'set and get of keywords via direct accessor'; + is $asset->get('keywords'), 'chess set', 'via get method'; +} + +sub t_05_purge : Test(3) { + note "purge"; + my $test = shift; + my $session = $test->session; + my ($tag, $asset, @parents) = $test->getAnchoredAsset(); + my @tables = $asset->meta->get_tables; + ok $asset->purge, 'purge returns true if it was purged'; + throws_ok { WebGUI::Asset->newById($session, $asset->assetId); } 'WebGUI::Error::InvalidParam', 'Unable to fetch asset by assetId now'; + my $exists_in_table = 0; + foreach my $table (@tables) { + $exists_in_table ||= $session->db->quickScalar("select count(*) from `$table` where assetId=?",[$asset->assetId]); + } + ok ! $exists_in_table, 'assetId removed from all asset tables'; +} 1; From 14d249d3f03d65f57e09c2b7489c0bbc589221f6 Mon Sep 17 00:00:00 2001 From: Scott Walters Date: Fri, 28 May 2010 08:38:38 -0400 Subject: [PATCH 075/101] stale PID file detection -- previous patch cleanup and supress uninit warning --- sbin/spectre.pl | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sbin/spectre.pl b/sbin/spectre.pl index 13bbd8954..ad3cf8d20 100755 --- a/sbin/spectre.pl +++ b/sbin/spectre.pl @@ -105,10 +105,9 @@ elsif ($daemon) { die "Spectre is already running.\n"; } elsif (-e $pidFileName){ - # oh, ffs ... die "pidFile $pidFileName already exists\n"; open my $pidFile, '<', $pidFileName or die "$pidFileName: $!"; (my $pid) = readline $pidFile; - chomp $pid; + chomp $pid if defined $pid; if(defined $pid and $pid =~ m/^(\d+)$/) { if(kill 0, $1) { die "$0: already running as PID $1"; From 636ca8ae8667c8e9ae73d9b88226a2bac2978401 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 28 May 2010 11:58:43 -0700 Subject: [PATCH 076/101] Update AssetHelper/Lock test. Missing use line in the module itself. --- lib/WebGUI/AssetHelper/Lock.pm | 4 ++-- t/AssetHelper/Lock.t | 16 +++++++--------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/lib/WebGUI/AssetHelper/Lock.pm b/lib/WebGUI/AssetHelper/Lock.pm index 131846d7b..628f0bd80 100644 --- a/lib/WebGUI/AssetHelper/Lock.pm +++ b/lib/WebGUI/AssetHelper/Lock.pm @@ -2,6 +2,7 @@ package WebGUI::AssetHelper::Lock; use strict; use Class::C3; +use WebGUI::International; use base qw/WebGUI::AssetHelper/; =head1 LEGAL @@ -18,7 +19,7 @@ use base qw/WebGUI::AssetHelper/; =head1 NAME -Package WebGUI::AssetHelper::Locks +Package WebGUI::AssetHelper::Lock =head1 DESCRIPTION @@ -52,7 +53,6 @@ sub process { } $asset = $asset->addRevision; - return { message => sprintf($i18n->get('locked asset'), $asset->getTitle), }; diff --git a/t/AssetHelper/Lock.t b/t/AssetHelper/Lock.t index 0ce0c236e..0d0145ca0 100644 --- a/t/AssetHelper/Lock.t +++ b/t/AssetHelper/Lock.t @@ -27,12 +27,6 @@ use WebGUI::AssetHelper::Lock; # Init my $session = WebGUI::Test->session; - -#---------------------------------------------------------------------------- -# Tests - -plan tests => 3; # Increment this number for each test you create - #---------------------------------------------------------------------------- # put your tests here @@ -54,7 +48,7 @@ my $versionTag = WebGUI::VersionTag->getWorking($session); $versionTag->commit; addToCleanup($versionTag); -$newPage = $newPage->cloneFromDb; +$newPage = WebGUI::Asset->newById($session, $newPage->assetId); $session->user({userId => 1}); $output = WebGUI::AssetHelper::Lock->process($newPage); @@ -76,11 +70,13 @@ cmp_deeply( '... locks the asset' ); -$newPage = $newPage->cloneFromDb; - my $versionTag2 = WebGUI::VersionTag->getWorking($session); addToCleanup($versionTag2); +$newPage = WebGUI::Asset->newById($session, $newPage->assetId); +ok $newPage->isLocked, 'Asset is locked, and ready for next test'; +is $newPage->getRevisionCount, 2, 'new revision added'; + $session->user({userId => $editor->getId}); $output = WebGUI::AssetHelper::Lock->process($newPage); cmp_deeply( @@ -90,3 +86,5 @@ cmp_deeply( }, '... returns an error message if the asset is already locked' ); + +done_testing; From eeef1a23494a8448a36b084b1dc3a09acf5d1b28 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 28 May 2010 11:59:52 -0700 Subject: [PATCH 077/101] Add tests for setVersionLock, no more test plans. --- t/Asset.t | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/t/Asset.t b/t/Asset.t index 2193794f7..1063f4706 100644 --- a/t/Asset.t +++ b/t/Asset.t @@ -21,7 +21,6 @@ use Test::Deep; use Test::Exception; use WebGUI::Exception; -plan tests => 65; my $session = WebGUI::Test->session; @@ -217,6 +216,32 @@ my $session = WebGUI::Test->session; $session->db->write("delete from assetData where assetId=?", [$testId]); } +{ + note "setVersionLock"; + my $testId1 = 'wg8TestAsset0000000001'; + my $testId2 = 'wg8TestAsset0000000002'; + my $now = time(); + my $baseLineage = $session->db->quickScalar('select lineage from asset where assetId=?',['PBasset000000000000002']); + my $testLineage = $baseLineage. '909090'; + $session->db->write("insert into asset (assetId, className, lineage) VALUES (?,?,?)", [$testId1, 'WebGUI::Asset', $testLineage]); + $session->db->write("insert into assetData (assetId, revisionDate, status) VALUES (?,?,?)", [$testId1, $now, 'approved']); + my $testLineage2 = $testLineage . '000001'; + $session->db->write("insert into asset (assetId, className, parentId, lineage) VALUES (?,?,?,?)", [$testId2, 'WebGUI::Asset', $testId1, $testLineage2]); + $session->db->write("insert into assetData (assetId, revisionDate) VALUES (?,?)", [$testId2, $now]); + + my $testAsset = WebGUI::Asset->new($session, $testId2, $now); + my $originalSessionUser = $session->user->userId; + $session->user({userId => 7}); + $testAsset->setVersionLock; + is $testAsset->isLockedBy, 7, 'locked by userId 7'; + ok $testAsset->isLocked, 'asset is locked'; + is $session->db->quickScalar('select isLockedBy from asset where assetId=?',[$testId2]), 7, 'userId written to db'; + + $session->db->write("delete from asset where assetId like 'wg8TestAsset00000%'"); + $session->db->write("delete from assetData where assetId like 'wg8TestAsset00000%'"); + $session->user({userId => $originalSessionUser}); +} + { note "getParent"; my $testId1 = 'wg8TestAsset0000000001'; @@ -254,21 +279,28 @@ my $session = WebGUI::Test->session; $session->db->write("insert into assetData (assetId, revisionDate) VALUES (?,?)", [$testId2, $revisionDate]); my $testAsset = WebGUI::Asset->new($session, $testId2, $revisionDate); + my $originalSessionUser = $session->user->userId; + $session->user({userId => 7}); $testAsset->title('test title 43'); $testAsset->write(); my $tag = WebGUI::VersionTag->getWorking($session); my $revAsset = $testAsset->addRevision({}, $now); + my $revAssetDb = $revAsset->cloneFromDb; isa_ok $revAsset, 'WebGUI::Asset'; is $revAsset->revisionDate, $now, 'revisionDate set correctly on new revision'; is $revAsset->title, 'test title 43', 'data fetch from database correct'; is $revAsset->revisedBy, $session->user->userId, 'revisedBy is current session user'; is $revAsset->tagId, $tag->getId, 'tagId is current working tagId'; + ok $revAsset->isLocked, 'new revision is locked'; + is $revAsset->isLockedBy, '7', 'locked by userId 7'; + is $revAssetDb->isLockedBy, '7', 'database jives with asset data'; my $count = $session->db->quickScalar('SELECT COUNT(*) from assetData where assetId=?',[$testId2]); is $count, 2, 'two records in the database'; addToCleanup($tag); $session->db->write("delete from asset where assetId like 'wg8TestAsset00000%'"); $session->db->write("delete from assetData where assetId like 'wg8TestAsset00000%'"); + $session->user({userId => $originalSessionUser}); } { @@ -325,3 +357,5 @@ my $session = WebGUI::Test->session; my $classes = WebGUI::Asset->valid_parent_classes; cmp_deeply($classes, [qw/WebGUI::Asset/], 'Any asset okay'); } + +done_testing; From c31fee588c592e474390a088deac9f12f498b286 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 28 May 2010 12:00:08 -0700 Subject: [PATCH 078/101] No test planning. --- t/Definition/Asset.t | 1 + 1 file changed, 1 insertion(+) diff --git a/t/Definition/Asset.t b/t/Definition/Asset.t index 1f96a843b..3e6c89918 100644 --- a/t/Definition/Asset.t +++ b/t/Definition/Asset.t @@ -258,3 +258,4 @@ use WebGUI::Test; $object->defaulted(undef); is $object->defaulted(), undef, 'Moose setters accept undef'; } +done_testing; From 483acbc3826790253e45dae4d97be7e9b714027e Mon Sep 17 00:00:00 2001 From: Scott Walters Date: Mon, 31 May 2010 14:39:36 -0400 Subject: [PATCH 079/101] Revert "Calls to set() and update() set attributes as well as "properties"." This reverts commit 57fe0721ab6049e02c421cf2b1cb387f4eed42da. --- lib/WebGUI/AssetVersioning.pm | 3 +-- lib/WebGUI/Definition/Role/Object.pm | 23 ++++------------------- 2 files changed, 5 insertions(+), 21 deletions(-) diff --git a/lib/WebGUI/AssetVersioning.pm b/lib/WebGUI/AssetVersioning.pm index ed2ebf409..eeefe9f3b 100644 --- a/lib/WebGUI/AssetVersioning.pm +++ b/lib/WebGUI/AssetVersioning.pm @@ -126,8 +126,7 @@ sub addRevision { $session->db->commit; # current values, and the user set properties - # my %mergedProperties = (%{$self->get}, %{$properties}, (status => 'pending', revisedBy => $session->user->userId, tagId => $workingTag->getId), ); # XXX results in the setting of read-only properties and nothing else seems to be done with this other than just set them again - my %mergedProperties = ( %{$properties}, status => 'pending', revisedBy => $session->user->userId, tagId => $workingTag->getId, ); + my %mergedProperties = (%{$self->get}, %{$properties}, (status => 'pending', revisedBy => $session->user->userId, tagId => $workingTag->getId), ); #Instantiate new revision and fill with real data my $newVersion = WebGUI::Asset->newById($session, $self->getId, $now); diff --git a/lib/WebGUI/Definition/Role/Object.pm b/lib/WebGUI/Definition/Role/Object.pm index e00358d4d..4c1c74a79 100644 --- a/lib/WebGUI/Definition/Role/Object.pm +++ b/lib/WebGUI/Definition/Role/Object.pm @@ -85,23 +85,13 @@ is not an attribute of the object, then it is silently ignored. =cut sub set { - my $self = shift; my $properties = @_ % 2 ? shift : { @_ }; - my %seen; - - my @settable = grep { ! $seen{$_}++ } ( - $self->getProperties, # $self->meta->get_all_property_list, # same as $self->getProperties - $self->getReadableAttributes, - ); - - for my $attribute ( @settable ) { - next unless exists $properties->{$attribute}; - $self->$attribute( $properties->{$attribute} ); + my @orderedProperties = $self->getProperties; + KEY: for my $property ( @orderedProperties ) { + next KEY unless exists $properties->{$property}; + $self->$property($properties->{$property}); } - - # ignore unknown properties - return 1; } @@ -191,10 +181,5 @@ sub getProperties { return $self->meta->get_all_property_list; } -sub getReadableAttributes { - my $self = shift; - return map $_->name, grep $_->has_accessor || $_->has_writer, $self->meta->get_all_attributes; -} - 1; From 74b500e443795e672bf8ac3ba2a4cd776c57a4cf Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Wed, 2 Jun 2010 16:37:00 -0700 Subject: [PATCH 080/101] Tests for properties that should be returned by get, and some that should not. Done by hash inspection. --- t/Asset.t | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/t/Asset.t b/t/Asset.t index 1063f4706..3c04ab6d0 100644 --- a/t/Asset.t +++ b/t/Asset.t @@ -128,6 +128,20 @@ my $session = WebGUI::Test->session; } +{ + note "get, specific properties"; + my $asset = WebGUI::Asset->new({ + session => $session, + }); + my $properties = $asset->get(); + ok !exists $properties->{session}, 'no session'; + ok exists $properties->{keywords}, 'keywords'; ##Test for function later + ok exists $properties->{assetId}, 'assetId'; + ok exists $properties->{revisionDate}, 'assetId'; + ok exists $properties->{parentId}, 'parentId'; + ok exists $properties->{lineage}, 'lineage'; +} + { note "getClassById"; my $class; From 7b274989126ceb5c3d882c2a73b7709ff38ef5ae Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Wed, 2 Jun 2010 19:59:14 -0700 Subject: [PATCH 081/101] Change ->get to direct object accessors. --- lib/WebGUI/AssetClipboard.pm | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/WebGUI/AssetClipboard.pm b/lib/WebGUI/AssetClipboard.pm index 389f0cc09..51b370912 100644 --- a/lib/WebGUI/AssetClipboard.pm +++ b/lib/WebGUI/AssetClipboard.pm @@ -199,18 +199,19 @@ sub paste { my $outputSub = shift; my $session = $self->session; my $pastedAsset = WebGUI::Asset->newById($session,$assetId); - return 0 unless ($self->get("state") eq "published"); + return 0 unless ($self->state eq "published"); return 0 unless ($pastedAsset->canPaste()); ##Allow pasted assets to have a say about pasting. # Don't allow a shortcut to create an endless loop - return 0 if ($pastedAsset->get("className") eq "WebGUI::Asset::Shortcut" && $pastedAsset->get("shortcutToAssetId") eq $self->getId); + return 0 if ($pastedAsset->isa("WebGUI::Asset::Shortcut") && $pastedAsset->shortcutToAssetId eq $self->getId); my $i18n=WebGUI::International->new($session, 'Asset'); $outputSub->(sprintf $i18n->get('pasting %s'), $pastedAsset->getTitle) if defined $outputSub; - if ($self->getId eq $pastedAsset->get("parentId") || $pastedAsset->setParent($self)) { + if ($self->getId eq $pastedAsset->parentId || $pastedAsset->setParent($self)) { $pastedAsset->publish(['clipboard','clipboard-limbo']); # Paste only clipboard items $pastedAsset->updateHistory("pasted to parent ".$self->getId); # Update lineage in search index. + $self->purgeCache; my $updateAssets = $pastedAsset->getLineage(['self', 'descendants'], {returnObjects => 1}); foreach (@{$updateAssets}) { From e3de7cd162e58f789465f07298e7e3254ae1def3 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Wed, 2 Jun 2010 19:59:32 -0700 Subject: [PATCH 082/101] Update object accessors, fix a problem with pasting. --- t/AssetHelper/Cut.t | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/t/AssetHelper/Cut.t b/t/AssetHelper/Cut.t index 50adabedd..dfb75ae4d 100644 --- a/t/AssetHelper/Cut.t +++ b/t/AssetHelper/Cut.t @@ -31,11 +31,6 @@ my $session = WebGUI::Test->session; #---------------------------------------------------------------------------- # Tests -plan tests => 5; # Increment this number for each test you create - -#---------------------------------------------------------------------------- -# put your tests here - my $output; my $home = WebGUI::Asset->getDefault($session); @@ -69,11 +64,15 @@ cmp_deeply( }, 'AssetHelper/Cut returns a message and a redirect' ); -is $safe_page->get('state'), 'clipboard', '... and the asset was really cut'; +is $safe_page->state, 'clipboard', '... and the asset was really cut'; -$home->paste($safe_page->getId); +$session->asset($home); +ok $home->paste($safe_page->getId), 'page pasted correctly'; -$safe_page = $safe_page->cloneFromDb(); -is $safe_page->get('state'), 'published', 'reset asset for further testing'; +$session->cache->clear; +my $safe_page2 = WebGUI::Asset->newById($session, $safe_page->assetId); +is $safe_page2->state, 'published', 'reset asset for further testing'; + +done_testing(); #vim:ft=perl From dcb9bacc8361b97e1539191b33ffd101c3cf0bb1 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Wed, 2 Jun 2010 20:23:22 -0700 Subject: [PATCH 083/101] One plan per test, please! --- t/Definition/Asset.t | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/t/Definition/Asset.t b/t/Definition/Asset.t index 3e6c89918..6abcf9645 100644 --- a/t/Definition/Asset.t +++ b/t/Definition/Asset.t @@ -15,7 +15,7 @@ no warnings qw(uninitialized); use FindBin; use lib "$FindBin::Bin/../lib"; -use Test::More 'no_plan'; #tests => 1; +use Test::More; use Test::Deep; use Test::Exception; use WebGUI::Test; From 2976539482d8c25572efbff750fd27aab3211ed3 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Wed, 2 Jun 2010 20:26:39 -0700 Subject: [PATCH 084/101] Content check via truthiness. --- t/Macro/UsersOnline.t | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/t/Macro/UsersOnline.t b/t/Macro/UsersOnline.t index d3966fa35..613ef9717 100644 --- a/t/Macro/UsersOnline.t +++ b/t/Macro/UsersOnline.t @@ -39,7 +39,7 @@ ok(defined $defTemplate, 'default template is present'); # Call with default values my $html = WebGUI::Macro::UsersOnline::process($session); -cmp_ok((length $html), '>', 0, 'call with default template and values returns some output'); +ok($html, 'call with default template and values returns some output'); # Test labels ------------------------------------------------------------- From 9a1c5c9c0329798be4b81cd3fc5f5f2c18e2f4bb Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 3 Jun 2010 15:40:07 -0700 Subject: [PATCH 085/101] Cart cleanup from leaky PayDriver test. --- t/Shop/PayDriver.t | 1 + 1 file changed, 1 insertion(+) diff --git a/t/Shop/PayDriver.t b/t/Shop/PayDriver.t index d4a87acfd..362b37800 100644 --- a/t/Shop/PayDriver.t +++ b/t/Shop/PayDriver.t @@ -254,6 +254,7 @@ isnt( ####################################################################### my $cart = $driver->getCart; +WebGUI::Test->addToCleanup($cart); isa_ok ($cart, 'WebGUI::Shop::Cart', 'getCart returns an instantiated WebGUI::Shop::Cart object'); ####################################################################### From 4fb7933e34dc9cfd2c29e3ad7f9fc96c822dcde3 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 3 Jun 2010 16:11:11 -0700 Subject: [PATCH 086/101] Exception handling for getSku. --- lib/WebGUI/Shop/CartItem.pm | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/WebGUI/Shop/CartItem.pm b/lib/WebGUI/Shop/CartItem.pm index 89f398ebb..cddb5b4b1 100644 --- a/lib/WebGUI/Shop/CartItem.pm +++ b/lib/WebGUI/Shop/CartItem.pm @@ -173,9 +173,10 @@ Returns an instanciated WebGUI::Asset::Sku object for this cart item. sub getSku { my ($self) = @_; - my $asset = ''; - $asset = WebGUI::Asset->newById($self->cart->session, $self->get("assetId")); - $asset->applyOptions($self->get("options")) if $asset; + my $asset = eval { WebGUI::Asset->newById($self->cart->session, $self->get("assetId")); }; + if (!Exception::Class->caught) { + $asset->applyOptions($self->get("options")); + } return $asset; } @@ -229,7 +230,7 @@ Removes this item from the cart and calls $sku->onRemoveFromCart. See also delet sub remove { my $self = shift; - my $sku = $self->getSku; + my $sku = eval { $self->getSku; }; $sku->onRemoveFromCart($self) if $sku; return $self->delete; } From 0d2ac6a858c3980b879db5e32d85c5c11e22cf13 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 3 Jun 2010 16:11:56 -0700 Subject: [PATCH 087/101] Get pending assets for cleanup. --- t/lib/WebGUI/Test.pm | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/t/lib/WebGUI/Test.pm b/t/lib/WebGUI/Test.pm index 86898059c..e8e5f354c 100644 --- a/t/lib/WebGUI/Test.pm +++ b/t/lib/WebGUI/Test.pm @@ -812,6 +812,10 @@ Example call: my ($class, $ident) = @_; return $class->new($CLASS->session, $ident); }, + 'WebGUI::Asset' => sub { + my ($class, $ident) = @_; + return WebGUI::Asset->newPending($CLASS->session, $ident); + }, 'WebGUI::Storage' => sub { my ($class, $ident) = @_; return WebGUI::Storage->get($CLASS->session, $ident); From 3ccf71ae0b243a667ded69817bad9f78d57bbbe0 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 3 Jun 2010 16:12:14 -0700 Subject: [PATCH 088/101] Better test cleanups. Hopefully, this fixes the RemoveOldCarts activity. --- t/Shop/PayDriver/Ogone.t | 1 + t/Shop/ShipDriver/FlatRate.t | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/t/Shop/PayDriver/Ogone.t b/t/Shop/PayDriver/Ogone.t index 8b0749155..ce68f5459 100644 --- a/t/Shop/PayDriver/Ogone.t +++ b/t/Shop/PayDriver/Ogone.t @@ -353,6 +353,7 @@ isnt( ####################################################################### my $cart = $driver->getCart; +WebGUI::Test->addToCleanup($cart); isa_ok ($cart, 'WebGUI::Shop::Cart', 'getCart returns an instantiated WebGUI::Shop::Cart object'); ####################################################################### diff --git a/t/Shop/ShipDriver/FlatRate.t b/t/Shop/ShipDriver/FlatRate.t index d8202d48b..d5d4a94d1 100644 --- a/t/Shop/ShipDriver/FlatRate.t +++ b/t/Shop/ShipDriver/FlatRate.t @@ -263,7 +263,6 @@ my $car = WebGUI::Asset->getImportNode($session)->addChild({ title => 'Automobiles', isShippingRequired => 1, }); -WebGUI::Test->addToCleanup($car); my $crappyCar = $car->setCollateral('variantsJSON', 'variantId', 'new', { From 95b6b66d694364ba59223c29475590e0fe02866f Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 3 Jun 2010 16:56:19 -0700 Subject: [PATCH 089/101] fix a problem with the generated HTML id. --- lib/WebGUI/Asset/File/Image.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/WebGUI/Asset/File/Image.pm b/lib/WebGUI/Asset/File/Image.pm index 6720a909a..7e9318d16 100644 --- a/lib/WebGUI/Asset/File/Image.pm +++ b/lib/WebGUI/Asset/File/Image.pm @@ -244,7 +244,7 @@ sub view { $var{fileIcon} = $self->getFileIconUrl; $var{thumbnail} = $self->getThumbnailUrl; $var{annotateJs} = $crop_js . $domMe; - $var{parameters} .= sprintf("id=%s", $self->getId); + $var{parameters} .= sprintf(q{ id="%s"}, $self->getId); my $out = $self->processTemplate(\%var,undef,$self->{_viewTemplate}); if (!$session->var->isAdminOn && $self->cacheTimeout > 10) { $cache->set( $cacheKey, $out, $self->get("cacheTimeout") ); From 15faef5d0102e5356a4a51470bca77a89ac810eb Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 3 Jun 2010 16:56:52 -0700 Subject: [PATCH 090/101] Fix caching a subroutine ref. Small test cleanups. --- t/Asset/File/Image.t | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/t/Asset/File/Image.t b/t/Asset/File/Image.t index 0268b08b8..24de499a9 100644 --- a/t/Asset/File/Image.t +++ b/t/Asset/File/Image.t @@ -31,7 +31,6 @@ use WebGUI::Form::File; use Test::More; # increment this value for each test you create use Test::Deep; use Data::Dumper; -plan tests => 15; my $session = WebGUI::Test->session; @@ -106,7 +105,7 @@ $templateMock->set_isa('WebGUI::Asset::Template'); $templateMock->set_always('getId', $templateId); $templateMock->set_true('prepare'); my $templateVars; -$templateMock->mock('process', sub { $templateVars = $_[1]; } ); +$templateMock->mock('process', sub { $templateVars = $_[1]; return ''; } ); $asset->update({ parameters => 'alt="alternate"', @@ -123,7 +122,9 @@ $asset->update({ } $versionTag->commit; -addToCleanup($versionTag); +WebGUI::Test->addToCleanup($versionTag); + +done_testing(); sub isnt_array { my ($a, $b) = @_; From 2ad02b32e10bb8e287f5c7d6e02a43ad20c7e6ec Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 3 Jun 2010 17:09:18 -0700 Subject: [PATCH 091/101] Codify in 1 place how to skip autocommit workflows, and notification. --- t/lib/WebGUI/Test.pm | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/t/lib/WebGUI/Test.pm b/t/lib/WebGUI/Test.pm index e8e5f354c..ee21fb5bb 100644 --- a/t/lib/WebGUI/Test.pm +++ b/t/lib/WebGUI/Test.pm @@ -496,6 +496,25 @@ sub webguiBirthday { #---------------------------------------------------------------------------- +=head2 getAssetSkipCoda ( ) + +Coded here for the sake of consistency, this returns everything that should be +appended to calls to addChild to autogenerate ids, revisionDates, and to skip +autoCommit workflows, and notifications. + +=cut + +sub getAssetSkipCoda { + return undef, + undef, + { + skipAutoCommitWorkflows => 1, + skipNotification => 1, + }; +} + +#---------------------------------------------------------------------------- + =head2 getSmokeLDAPProps ( ) Returns a hashref of properties for connecting to smoke's LDAP server. From cd97f2e0ab8862be44eaafbc226d25d4938b9b7d Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 3 Jun 2010 17:09:58 -0700 Subject: [PATCH 092/101] Remove use_ok, SKIP, plan, END block. --- t/Asset/Wobject/StoryArchive.t | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/t/Asset/Wobject/StoryArchive.t b/t/Asset/Wobject/StoryArchive.t index c51e8a226..b9f556ab2 100644 --- a/t/Asset/Wobject/StoryArchive.t +++ b/t/Asset/Wobject/StoryArchive.t @@ -63,31 +63,21 @@ $canPostMaker->prepare({ fail => [1, $reader ], }); -my $tests = 50 - + $canPostMaker->plan - ; -plan tests => 1 - + $tests; - #---------------------------------------------------------------------------- # put your tests here -my $class = 'WebGUI::Asset::Wobject::StoryArchive'; -my $loaded = use_ok($class); +use_ok('WebGUI::Asset::Wobject::StoryArchive'); my $storage; my $versionTag; my $creationDateSth = $session->db->prepare('update asset set creationDate=? where assetId=?'); -my @skipAutoCommit = (undef, undef, { skipAutoCommitWorkflows => 1 }); +my @skipAutoCommit = WebGUI::Test->addAssetSkipCoda; -SKIP: { - -skip "Unable to load module $class", $tests unless $loaded; my $home = WebGUI::Asset->getDefault($session); $archive = $home->addChild({ - className => $class, + className => 'WebGUI::Asset::Wobject::StoryArchive', title => 'My Stories', url => '/home/mystories', styleTemplateId => $home->get('styleTemplateId'), @@ -661,13 +651,11 @@ $archive->update({ url => '/home/mystories.arch' }); is($archive->getKeywordStaticURL('bar'), '/home/mystories/keyword_bar.html', '... correct URL with file extension'); $archive->update({ url => '/home/mystories' }); -} + +$creationDateSth->finish; +done_testing(); #---------------------------------------------------------------------------- -# Cleanup -END { - $creationDateSth->finish; -} sub simpleHrefParser { my ($text) = @_; From b5d17576b0f041f8a204257762a5f6a6a56e941c Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Thu, 3 Jun 2010 19:37:57 -0700 Subject: [PATCH 093/101] change some ->gets to direct accessors. --- t/Asset/Wobject/Survey.t | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/t/Asset/Wobject/Survey.t b/t/Asset/Wobject/Survey.t index 481dddb0e..a1d9d2632 100644 --- a/t/Asset/Wobject/Survey.t +++ b/t/Asset/Wobject/Survey.t @@ -66,9 +66,9 @@ my $responseId = $survey->responseId; my $s = WebGUI::Asset::Wobject::Survey->newByResponseId($session, $responseId); is($s->getId, $survey->getId, 'newByResponseId returns same Survey'); } -is($survey->get('maxResponsesPerUser'), 1, 'maxResponsesPerUser defaults to 1'); +is($survey->maxResponsesPerUser, 1, 'maxResponsesPerUser defaults to 1'); ok($survey->canTakeSurvey, '..which means user can take survey'); -is($survey->get('revisionDate'), $session->db->quickScalar('select revisionDate from Survey_response where Survey_responseId = ?', [$responseId]), 'Current revisionDate used'); +is($survey->revisionDate, $session->db->quickScalar('select revisionDate from Survey_response where Survey_responseId = ?', [$responseId]), 'Current revisionDate used'); #################################################### # @@ -234,7 +234,7 @@ cmp_deeply(from_json($surveyEnd), { type => 'forward', url => '/getting_started' isa_ok($newerSurvey, 'WebGUI::Asset::Wobject::Survey', 'After change, re-retrieved Survey instance'); is($newerSurvey->getId, $surveyId, '..which is the same survey'); is($newerSurvey->getSurveyJSON->section([0])->{text}, 'newer text', '..with updated text'); - ok($newerSurvey->get('revisionDate') > $revisionDate, '..and newer revisionDate'); + ok($newerSurvey->revisionDate > $revisionDate, '..and newer revisionDate'); # Create another response (this one will use the new revision) my $newUser = WebGUI::User->new( $session, 'new' ); From 7933e12ab51c676141b2e7c35fcb4ec883119aca Mon Sep 17 00:00:00 2001 From: Scott Walters Date: Thu, 3 Jun 2010 20:04:01 -0400 Subject: [PATCH 094/101] get() shouldn't return session; fixes the Asset.t "get, specific properties - no session" test --- lib/WebGUI/Definition/Role/Object.pm | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/WebGUI/Definition/Role/Object.pm b/lib/WebGUI/Definition/Role/Object.pm index 4c1c74a79..9d1133e15 100644 --- a/lib/WebGUI/Definition/Role/Object.pm +++ b/lib/WebGUI/Definition/Role/Object.pm @@ -68,6 +68,7 @@ sub get { return undef; } my %properties = map { $_ => scalar $self->$_ } $self->meta->get_all_attributes_list; + delete $properties{session}; return \%properties; } From 4eca8bb99336eb05fd754b6a26074bb0561b6ca1 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 4 Jun 2010 10:17:16 -0700 Subject: [PATCH 095/101] Commit the initial Survey for the test. --- t/Asset/Wobject/Survey.t | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/t/Asset/Wobject/Survey.t b/t/Asset/Wobject/Survey.t index a1d9d2632..e430ab854 100644 --- a/t/Asset/Wobject/Survey.t +++ b/t/Asset/Wobject/Survey.t @@ -32,7 +32,9 @@ my $import_node = WebGUI::Asset->getImportNode($session); # Create a Survey $survey = $import_node->addChild( { className => 'WebGUI::Asset::Wobject::Survey', } ); my $tag = WebGUI::VersionTag->getWorking($session); -WebGUI::Test->assetsToPurge($survey); +$tag->commit; +$survey = $survey->cloneFromDb; +WebGUI::Test->addToCleanup($survey); isa_ok($survey, 'WebGUI::Asset::Wobject::Survey'); my $sJSON = $survey->getSurveyJSON; From 8c759ed7bcdaaa0ec6235a4469e4fa767df583a5 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 4 Jun 2010 11:33:06 -0700 Subject: [PATCH 096/101] Implement keywords differently (successfully) in the Asset class. Extra tests to verify it in Asset.t --- lib/WebGUI/Asset.pm | 22 +++++++--------------- lib/WebGUI/Definition/Meta/Class.pm | 15 +++++++++++++++ lib/WebGUI/Definition/Meta/Property.pm | 2 ++ lib/WebGUI/Definition/Role/Object.pm | 4 ++-- t/Asset.t | 19 ++++++++++++++++++- 5 files changed, 44 insertions(+), 18 deletions(-) diff --git a/lib/WebGUI/Asset.pm b/lib/WebGUI/Asset.pm index c8c86801a..73bff8518 100644 --- a/lib/WebGUI/Asset.pm +++ b/lib/WebGUI/Asset.pm @@ -307,25 +307,16 @@ sub _build_className { } has keywords => ( is => 'rw', - init_arg => undef, builder => '_build_assetKeywords', lazy => 1, + traits => [ 'WebGUI::Definition::Meta::Settable' ], ); sub _build_assetKeywords { - my $session = shift->session; - return WebGUI::Keyword->new($session); -} - -around keywords => sub { - my $orig = shift; my $self = shift; - if (@_) { - return $self->$orig->setKeywordsForAsset({asset => $self, keywords => $_[0], }); - } - else { - return $self->$orig->getKeywordsForAsset({asset => $self}); - } -}; + my $session = $self->session; + my $keywords = WebGUI::Keyword->new($session); + return $keywords->getKeywordsForAsset({asset => $self, asArrayRef => 1 }); +} around BUILDARGS => sub { my $orig = shift; @@ -374,7 +365,7 @@ around BUILDARGS => sub { if (defined $properties) { $properties->{session} = $session; return $className->$orig($properties); - } + } $session->errorHandler->error("Something went wrong trying to instanciate a '$className' with assetId '$assetId', but I don't know what!"); return undef; }; @@ -2481,6 +2472,7 @@ sub write { # update the asset's size, which also purges the cache. $self->setSize(); + WebGUI::Keyword->new($self->session)->setKeywordsForAsset({ asset => $self, keywords => $self->keywords }); } diff --git a/lib/WebGUI/Definition/Meta/Class.pm b/lib/WebGUI/Definition/Meta/Class.pm index 112b7be2c..b3944fa0d 100644 --- a/lib/WebGUI/Definition/Meta/Class.pm +++ b/lib/WebGUI/Definition/Meta/Class.pm @@ -148,6 +148,21 @@ sub get_all_property_list { return @names; } +sub get_all_settable_list { + my $self = shift; + my @names = (); + my %seen = (); + foreach my $meta ($self->get_all_class_metas) { + push @names, + grep { !$seen{$_}++ } + map { $_->name } + sort { $a->insertion_order <=> $b->insertion_order } + grep { $_->does('WebGUI::Definition::Meta::Settable') } + $meta->get_attributes; + } + return @names; +} + #------------------------------------------------------------------- =head2 get_attributes ( ) diff --git a/lib/WebGUI/Definition/Meta/Property.pm b/lib/WebGUI/Definition/Meta/Property.pm index 7641827ed..efdaccde6 100644 --- a/lib/WebGUI/Definition/Meta/Property.pm +++ b/lib/WebGUI/Definition/Meta/Property.pm @@ -21,6 +21,8 @@ no warnings qw(uninitialized); our $VERSION = '0.0.1'; +with 'WebGUI::Definition::Meta::Settable'; + =head1 NAME Package WebGUI::Definition::Meta::Property diff --git a/lib/WebGUI/Definition/Role/Object.pm b/lib/WebGUI/Definition/Role/Object.pm index 9d1133e15..97aeb3551 100644 --- a/lib/WebGUI/Definition/Role/Object.pm +++ b/lib/WebGUI/Definition/Role/Object.pm @@ -62,7 +62,7 @@ sub get { my $self = shift; if (@_) { my $property = shift; - if ($self->meta->find_attribute_by_name($property)) { + if ($self->can($property)) { return $self->$property; } return undef; @@ -88,7 +88,7 @@ is not an attribute of the object, then it is silently ignored. sub set { my $self = shift; my $properties = @_ % 2 ? shift : { @_ }; - my @orderedProperties = $self->getProperties; + my @orderedProperties = $self->meta->get_all_settable_list; KEY: for my $property ( @orderedProperties ) { next KEY unless exists $properties->{$property}; $self->$property($properties->{$property}); diff --git a/t/Asset.t b/t/Asset.t index 3c04ab6d0..9487b8feb 100644 --- a/t/Asset.t +++ b/t/Asset.t @@ -20,6 +20,8 @@ use Test::More; use Test::Deep; use Test::Exception; use WebGUI::Exception; +use WebGUI::Asset; +use WebGUI::Keyword; my $session = WebGUI::Test->session; @@ -359,11 +361,26 @@ my $session = WebGUI::Test->session; my $asset = $default->addChild({ className => 'WebGUI::Asset::Snippet', }); - addToCleanup($asset); + WebGUI::Test->addToCleanup($asset); can_ok($asset, 'keywords'); $asset->keywords('chess set'); is ($asset->keywords, 'chess set', 'set and get of keywords via direct accessor'); is ($asset->get('keywords'), 'chess set', 'via get method'); + my $keygate = WebGUI::Keyword->new($session); + is $keygate->getKeywordsForAsset({assetId => $asset->getId}), '', 'not persisted to the db'; + $asset->write; + is $keygate->getKeywordsForAsset({assetId => $asset->assetId}), 'chess set', 'written to the db'; + + my $asset_copy = $asset->cloneFromDb; + is $asset->keywords, 'chess set', 'refreshed from db'; + + my $asset2 = $default->addChild({ + className => 'WebGUI::Asset::Snippet', + keywords => 'checkmate', + }); + WebGUI::Test->addToCleanup($asset2); + is $asset2->keywords, 'checkmate', 'keywords set on addChild'; + is $keygate->getKeywordsForAsset({assetId => $asset2->assetId}), 'checkmate', '... and persisted to the db'; } { From 193223c6787288c45c000aace538ec1a456f7a59 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 4 Jun 2010 13:19:03 -0700 Subject: [PATCH 097/101] Adding Settable flag for non-properties that should be handled by set/write. --- lib/WebGUI/Definition/Meta/Settable.pm | 39 ++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 lib/WebGUI/Definition/Meta/Settable.pm diff --git a/lib/WebGUI/Definition/Meta/Settable.pm b/lib/WebGUI/Definition/Meta/Settable.pm new file mode 100644 index 000000000..ac9e65e14 --- /dev/null +++ b/lib/WebGUI/Definition/Meta/Settable.pm @@ -0,0 +1,39 @@ +package WebGUI::Definition::Meta::Settable; + +=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 5.010; +use Moose::Role; +use namespace::autoclean; +no warnings qw(uninitialized); + +our $VERSION = '0.0.1'; + +=head1 NAME + +Package WebGUI::Definition::Meta::Property + +=head1 DESCRIPTION + +Moose-based meta class for all properties in WebGUI::Definition. + +=head1 SYNOPSIS + +WebGUI::Definition::Meta::Property extends Moose::Meta::Attribute to include +a read-only form method, that provides the form properties for the attribute. + +=cut + +1; From dd716fa79677df2659eec4732fae116f11f47f89 Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 4 Jun 2010 13:27:40 -0700 Subject: [PATCH 098/101] Fix the default URL for an Asset. It should be based on the parent, if available, and the menutitle. --- lib/WebGUI/Asset.pm | 6 ++++-- t/Asset.t | 11 +++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/WebGUI/Asset.pm b/lib/WebGUI/Asset.pm index 73bff8518..0eb0f86f5 100644 --- a/lib/WebGUI/Asset.pm +++ b/lib/WebGUI/Asset.pm @@ -80,7 +80,7 @@ property url => ( builder => '_default_url', ); sub _default_url { - return $_[0]->assetId; + return $_[0]->fixUrl; } around url => sub { @@ -701,7 +701,9 @@ sub fixUrl { # build a URL from the parent unless ($url) { - $url = $self->getParent->url; + if (my $parent = $self->getParent) { + $url = $parent->url; + } $url =~ s/(.*)\..*/$1/; $url .= '/'.$self->menuTitle; } diff --git a/t/Asset.t b/t/Asset.t index 9487b8feb..31af7bd84 100644 --- a/t/Asset.t +++ b/t/Asset.t @@ -389,4 +389,15 @@ my $session = WebGUI::Test->session; cmp_deeply($classes, [qw/WebGUI::Asset/], 'Any asset okay'); } +{ + note "url, inherited URLs from parent"; + my $home = WebGUI::Asset->getDefault($session); + my $asset = $home->addChild({ + className => 'WebGUI::Asset::Wobject::Article', + title => 'sub', + }); + WebGUI::Test->addToCleanup($asset); + is $asset->url, 'home/sub', 'by default, asset gets a url from the title, and the parent'; +} + done_testing; From 13e59e788cdf0e487a76802990c74d2b37f81dec Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 4 Jun 2010 13:31:52 -0700 Subject: [PATCH 099/101] EMS does not return session as a template variable any longer. --- t/Asset/Wobject/EventManagementSystem.t | 1 - 1 file changed, 1 deletion(-) diff --git a/t/Asset/Wobject/EventManagementSystem.t b/t/Asset/Wobject/EventManagementSystem.t index 204bce789..f0499805a 100644 --- a/t/Asset/Wobject/EventManagementSystem.t +++ b/t/Asset/Wobject/EventManagementSystem.t @@ -346,7 +346,6 @@ $templateMock->mock('process', sub { $templateVars = $_[1]; } ); 'eventSubmissionTemplateId' => ignore(), 'submittedLocationsList' => ignore(), 'keywords' => ignore(), - 'session' => ignore(), 'uiLevel' => ignore(), 'tickets_loop' => \@ticketArray, }, From 0a9785e2586770752781cb0a14c3cf7c152eeaee Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 4 Jun 2010 13:34:11 -0700 Subject: [PATCH 100/101] Fix a simple typo in the script. --- t/Asset/Wobject/StoryArchive.t | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/t/Asset/Wobject/StoryArchive.t b/t/Asset/Wobject/StoryArchive.t index b9f556ab2..4b0a058dc 100644 --- a/t/Asset/Wobject/StoryArchive.t +++ b/t/Asset/Wobject/StoryArchive.t @@ -72,7 +72,7 @@ my $storage; my $versionTag; my $creationDateSth = $session->db->prepare('update asset set creationDate=? where assetId=?'); -my @skipAutoCommit = WebGUI::Test->addAssetSkipCoda; +my @skipAutoCommit = WebGUI::Test->getAssetSkipCoda; my $home = WebGUI::Asset->getDefault($session); From 910a0a09dd1a80bb526a78fc3ccad9a229bf10ef Mon Sep 17 00:00:00 2001 From: Colin Kuskie Date: Fri, 4 Jun 2010 13:48:04 -0700 Subject: [PATCH 101/101] Upgrade this test for Definition. Something bad is still happening in export. --- t/AssetAspect/RssFeed.t | 14 +------------- t/lib/WebGUI/Asset/RssAspectDummy.pm | 13 +++++++++---- 2 files changed, 10 insertions(+), 17 deletions(-) diff --git a/t/AssetAspect/RssFeed.t b/t/AssetAspect/RssFeed.t index 466372e96..43c6f9088 100644 --- a/t/AssetAspect/RssFeed.t +++ b/t/AssetAspect/RssFeed.t @@ -48,6 +48,7 @@ my $dummy = WebGUI::Asset->getDefault($session)->addChild({ synopsis => 'Dummy Synopsis', description => 'Dummy Description', }); +WebGUI::Test->addToCleanup($dummy); ##################################################### # @@ -185,17 +186,4 @@ cmp_bag( 'exportAssetCollateral: feed files exported, shawshank.html file' ); -##################################################### -# -# exportAssetCollateral -# -##################################################### - -#---------------------------------------------------------------------------- -# Cleanup -END { - $dummy->purge; - my $tag = WebGUI::VersionTag->getWorking($session, 'noCreate'); - $tag->rollback if $tag; -} #vim:ft=perl diff --git a/t/lib/WebGUI/Asset/RssAspectDummy.pm b/t/lib/WebGUI/Asset/RssAspectDummy.pm index dc685b211..aa30036f0 100644 --- a/t/lib/WebGUI/Asset/RssAspectDummy.pm +++ b/t/lib/WebGUI/Asset/RssAspectDummy.pm @@ -15,9 +15,14 @@ package WebGUI::Asset::RssAspectDummy; =cut use strict; -use Tie::IxHash; -use Class::C3; -use base qw/WebGUI::AssetAspect::RssFeed WebGUI::Asset/; +use Moose; +use WebGUI::Definition::Asset; +extends 'WebGUI::Asset'; + +define assetName => 'RssAspectDummy'; +define icon => 'asset.gif'; + +with 'WebGUI::Role::Asset::RssFeed'; =head1 NAME @@ -25,7 +30,7 @@ Package WebGUI::Asset::RssAspectDummy =head1 DESCRIPTION -A dummy module for testing the RssAspect. The module really doesn't +A dummy module for testing the Rss Role. The module really doesn't do anything, except provide suport modules for testing. The module inherits directly from WebGUI::Asset.