diff --git a/lib/WebGUI/Asset.pm b/lib/WebGUI/Asset.pm
index d2ec4aedc..76cf07d52 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 {
@@ -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;
};
@@ -710,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;
}
@@ -845,26 +838,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 +856,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 +1701,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;
}
@@ -2468,6 +2474,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/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/EMSSubmissionForm.pm b/lib/WebGUI/Asset/EMSSubmissionForm.pm
index 085ecfd3d..89c396508 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
@@ -187,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 . '
' ;
- 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->newByDynamicClass($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 . '
';
+ 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
#-------------------------------------------------------------------
@@ -491,14 +499,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/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/File/GalleryFile/Photo.pm b/lib/WebGUI/Asset/File/GalleryFile/Photo.pm
index c288a6f3b..d9e0a9b9d 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;
@@ -214,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
@@ -223,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 } ];
}
#----------------------------------------------------------------------------
diff --git a/lib/WebGUI/Asset/File/Image.pm b/lib/WebGUI/Asset/File/Image.pm
index e80ab2fc0..7e9318d16 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;
@@ -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") );
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/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");
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/lib/WebGUI/Asset/Snippet.pm b/lib/WebGUI/Asset/Snippet.pm
index bb9ce3301..0285316ce 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/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/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) {
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"
;
diff --git a/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm b/lib/WebGUI/Asset/Wobject/GalleryAlbum.pm
index 9251d2efe..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 );
}
@@ -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 = eval { WebGUI::Asset->newById( $session, $destId ); };
# Return if destination file could not be instantiated
- unless ( $dest ) {
+ 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;
@@ -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
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();
+};
#-------------------------------------------------------------------
diff --git a/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm b/lib/WebGUI/Asset/Wobject/SyndicatedContent.pm
index e268629ab..785bc5d79 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;
@@ -216,6 +217,7 @@ sub getRssFeedItems {
author => $item->author,
guid => $item->guid,
);
+ push @items, \%feed_item;
}
return \@items;
}
@@ -293,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,
@@ -306,7 +309,7 @@ sub prepareView {
}
$template->prepare($self->getMetaDataAsTemplateVariables);
$self->{_viewTemplate} = $template;
-}
+};
#-------------------------------------------------------------------
@@ -358,63 +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(@_);
-}
-
-#-------------------------------------------------------------------
-
-=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;
-}
+override www_view => sub {
+ my $self = shift;
+ $self->session->http->setCacheControl($self->cacheTimeout);
+ super();
+};
__PACKAGE__->meta->make_immutable;
1;
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}) {
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/lib/WebGUI/AssetLineage.pm b/lib/WebGUI/AssetLineage.pm
index 2fb1d0b16..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;
@@ -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);
@@ -1000,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);
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;
}
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
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 = @_;
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/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;
diff --git a/lib/WebGUI/Definition/Role/Object.pm b/lib/WebGUI/Definition/Role/Object.pm
index 4c1c74a79..97aeb3551 100644
--- a/lib/WebGUI/Definition/Role/Object.pm
+++ b/lib/WebGUI/Definition/Role/Object.pm
@@ -62,12 +62,13 @@ 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;
}
my %properties = map { $_ => scalar $self->$_ } $self->meta->get_all_attributes_list;
+ delete $properties{session};
return \%properties;
}
@@ -87,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/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;
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;
}
diff --git a/lib/WebGUI/Group.pm b/lib/WebGUI/Group.pm
index 7551d4cc1..c4f7f25e4 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
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');
}
diff --git a/lib/WebGUI/Macro/PickLanguage.pm b/lib/WebGUI/Macro/PickLanguage.pm
index a1af2a40b..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->new($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 = ();
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;
+ }
}
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;
};
#-------------------------------------------------------------------
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;
}
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/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/;
diff --git a/lib/WebGUI/Shop/Transaction.pm b/lib/WebGUI/Shop/Transaction.pm
index 31190b8c0..7b3535232 100644
--- a/lib/WebGUI/Shop/Transaction.pm
+++ b/lib/WebGUI/Shop/Transaction.pm
@@ -632,7 +632,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/Shop/TransactionItem.pm b/lib/WebGUI/Shop/TransactionItem.pm
index 4e52b29a0..838e0eb2e 100644
--- a/lib/WebGUI/Shop/TransactionItem.pm
+++ b/lib/WebGUI/Shop/TransactionItem.pm
@@ -133,11 +133,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;
}
#-------------------------------------------------------------------
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'
;
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');
diff --git a/sbin/spectre.pl b/sbin/spectre.pl
index d1991ae9e..ad3cf8d20 100755
--- a/sbin/spectre.pl
+++ b/sbin/spectre.pl
@@ -105,8 +105,19 @@ elsif ($daemon) {
die "Spectre is already running.\n";
}
elsif (-e $pidFileName){
- die "pidFile $pidFileName already exists\n";
+ open my $pidFile, '<', $pidFileName or die "$pidFileName: $!";
+ (my $pid) = readline $pidFile;
+ chomp $pid if defined $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;
diff --git a/sbin/testEnvironment.pl b/sbin/testEnvironment.pl
index b815e0aed..be6a5d15b 100755
--- a/sbin/testEnvironment.pl
+++ b/sbin/testEnvironment.pl
@@ -143,6 +143,7 @@ checkModule("Readonly", "1.03" );
checkModule("Moose", "0.93" );
checkModule("MooseX::Storage", "0.23" );
checkModule("MooseX::NonMoose", '0.07' );
+checkModule("MooseX::Storage::Format::JSON","0.27" );
checkModule("namespace::autoclean", "0.09" );
checkModule("Business::PayPal::API", "0.62" );
checkModule("Locales", "0.10" );
diff --git a/t/Asset.t b/t/Asset.t
index 2193794f7..31af7bd84 100644
--- a/t/Asset.t
+++ b/t/Asset.t
@@ -20,8 +20,9 @@ use Test::More;
use Test::Deep;
use Test::Exception;
use WebGUI::Exception;
+use WebGUI::Asset;
+use WebGUI::Keyword;
-plan tests => 65;
my $session = WebGUI::Test->session;
@@ -129,6 +130,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;
@@ -217,6 +232,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 +295,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});
}
{
@@ -313,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';
}
{
@@ -325,3 +388,16 @@ my $session = WebGUI::Test->session;
my $classes = WebGUI::Asset->valid_parent_classes;
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;
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
;
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 } );
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');
####################################################
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');
diff --git a/t/Asset/EMSSubmissionForm.t b/t/Asset/EMSSubmissionForm.t
index dd3d16fd4..12f92c226 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;
@@ -353,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');
@@ -372,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/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;
- }
-}
-
-
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/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;
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();
-}
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) = @_;
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();
-}
-
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/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",
);
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.");
+
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/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';
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 {
}
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 = {};
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/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"');
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/EventManagementSystem.t b/t/Asset/Wobject/EventManagementSystem.t
index 10341bd7c..f0499805a 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,8 @@ $templateMock->mock('process', sub { $templateVars = $_[1]; } );
'eventSubmissionQueueTemplateId' => ignore(),
'eventSubmissionTemplateId' => ignore(),
'submittedLocationsList' => ignore(),
+ 'keywords' => ignore(),
+ 'uiLevel' => ignore(),
'tickets_loop' => \@ticketArray,
},
"www_printRemainingTickets: template variables valid"
diff --git a/t/Asset/Wobject/Gallery/00base.t b/t/Asset/Wobject/Gallery/00base.t
index 615bc9c1c..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->newByDynamicClass($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 9de44c814..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->newByDynamicClass($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();
-}
diff --git a/t/Asset/Wobject/GalleryAlbum/delete.t b/t/Asset/Wobject/GalleryAlbum/delete.t
index a590a81e4..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->newByDynamicClass( $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();
-}
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/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,
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({});
diff --git a/t/Asset/Wobject/StoryArchive.t b/t/Asset/Wobject/StoryArchive.t
index c51e8a226..4b0a058dc 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->getAssetSkipCoda;
-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) = @_;
diff --git a/t/Asset/Wobject/Survey.t b/t/Asset/Wobject/Survey.t
index 71581c481..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;
@@ -66,9 +68,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');
####################################################
#
@@ -210,7 +212,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]);
@@ -234,7 +236,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' );
diff --git a/t/Asset/Wobject/SyndicatedContent.t b/t/Asset/Wobject/SyndicatedContent.t
index 84fb34d2d..81a869d35 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, $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->remove($tbbUrl);
####################################################################
#
@@ -189,18 +187,16 @@ $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, $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->remove($oncpUrl);
diff --git a/t/Asset/permissions.t b/t/Asset/permissions.t
index f81c2967e..a16f54eeb 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
@@ -493,6 +163,7 @@ TODO: {
$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
@@ -515,388 +186,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');
-}
-
-################################################################
-#
-# newByDynamicClass
-#
-################################################################
-
-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');
-
-################################################################
-#
-# 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",
- },
- );
-}
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/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
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;
diff --git a/t/Definition/Asset.t b/t/Definition/Asset.t
index bdefc9671..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;
@@ -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/],
@@ -264,3 +258,4 @@ use WebGUI::Test;
$object->defaulted(undef);
is $object->defaulted(), undef, 'Moose setters accept undef';
}
+done_testing;
diff --git a/t/Group.t b/t/Group.t
index d1b43d765..a0843a06b 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,7 @@ 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;
@@ -684,5 +682,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');
}
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/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?
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 -------------------------------------------------------------
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');
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');
#######################################################################
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
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 082a7eaef..d5d4a94d1 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,7 +258,7 @@ undef $driver;
#
#######################################################################
-$car = WebGUI::Asset->getImportNode($session)->addChild({
+my $car = WebGUI::Asset->getImportNode($session)->addChild({
className => 'WebGUI::Asset::Sku::Product',
title => 'Automobiles',
isShippingRequired => 1,
@@ -302,8 +294,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 +308,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 +341,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 +368,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 +386,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;
- }
-}
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;
+}
#######################################################################
#
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;
+}
#######################################################################
#
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..d0f3ee923 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,599 @@ 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);
+
+#######################################################################
+#
+# new
+#
+#######################################################################
+
+my $taxer = WebGUI::Shop::TaxDriver::Generic->new($session);
+
+isa_ok($taxer, 'WebGUI::Shop::TaxDriver::Generic');
+
+isa_ok($taxer->session, 'WebGUI::Session', 'session method returns a session object');
+
+is($session->getId, $taxer->session->getId, 'session method returns OUR session object');
+
+#######################################################################
+#
+# getItems
+#
+#######################################################################
+
+my $taxIterator = $taxer->getItems;
+
+isa_ok($taxIterator, 'WebGUI::SQL::ResultSet');
+
+is($taxIterator->rows, 0, 'WebGUI ships with no predefined tax data');
+
+#######################################################################
+#
+# 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: '.$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
+##
+########################################################################
+
+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;
- skip 'Unable to load module WebGUI::Shop::TaxDriver::Generic', $tests unless $loaded;
-
- #######################################################################
- #
- # new
- #
- #######################################################################
-
- my $taxer = WebGUI::Shop::TaxDriver::Generic->new($session);
-
- isa_ok($taxer, 'WebGUI::Shop::TaxDriver::Generic');
-
- isa_ok($taxer->session, 'WebGUI::Session', 'session method returns a session object');
-
- is($session->getId, $taxer->session->getId, 'session method returns OUR session object');
-
- #######################################################################
- #
- # getItems
- #
- #######################################################################
-
- my $taxIterator = $taxer->getItems;
-
- isa_ok($taxIterator, 'WebGUI::SQL::ResultSet');
-
- is($taxIterator->rows, 0, 'WebGUI ships with no predefined tax data');
-
- #######################################################################
- #
- # add
- #
- #######################################################################
-
- my $e;
-
- eval{$taxer->add()};
+ my $originalChmod = (stat $taxFile)[2];
+ chmod oct(0000), $taxFile;
+ eval { $taxer->importTaxData($taxFile); };
$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::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 => '/path/to/nowhere',
+ brokenFile => $taxFile,
),
- 'importTaxData: error handling for file that does not exist in the filesystem',
+ 'importTaxData: error handling for file that that cannot be read',
);
- my $taxFile = WebGUI::Test->getTestCollateralPath('taxTables/goodTaxTable.csv');
+ chmod $originalChmod, $taxFile;
- 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,
- },
- ];
-
- ok(
- $taxer->importTaxData(
- $taxFile
- ),
- 'Good tax data inserted',
- );
-
- $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',
- );
-
- 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 => '',
+ 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 +670,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;
- }
}
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});
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();
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');
-}
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.
diff --git a/t/lib/WebGUI/Test.pm b/t/lib/WebGUI/Test.pm
index c87a15904..299ddc3c6 100644
--- a/t/lib/WebGUI/Test.pm
+++ b/t/lib/WebGUI/Test.pm
@@ -225,20 +225,20 @@ 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_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 {
@@ -248,6 +248,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) = @_;
@@ -473,6 +481,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.
@@ -790,6 +817,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);
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;