From e955c8ee4a967a899af67b9508441cc1aae70314 Mon Sep 17 00:00:00 2001
From: Lari Taskula <larit@student.uef.fi>
Date: Thu, 27 Aug 2015 14:09:54 +0000
Subject: [PATCH] Bug 13906: (follow-up) - MessageQueueFactory for adding
 messages to message_queue

---
 t/lib/TestObjects/MessageQueueFactory.pm | 152 +++++++++++++++++++++++++++++++
 t/lib/TestObjects/ObjectFactory.pm       |   5 +
 t/lib/TestObjects/objectFactories.t      |  50 ++++++++++
 3 files changed, 207 insertions(+)
 create mode 100644 t/lib/TestObjects/MessageQueueFactory.pm

diff --git a/t/lib/TestObjects/MessageQueueFactory.pm b/t/lib/TestObjects/MessageQueueFactory.pm
new file mode 100644
index 0000000..cb9352c
--- /dev/null
+++ b/t/lib/TestObjects/MessageQueueFactory.pm
@@ -0,0 +1,152 @@
+package t::lib::TestObjects::MessageQueueFactory;
+
+# Copyright Vaara-kirjastot 2015
+#
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 3 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with Koha; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+
+use Modern::Perl;
+use Carp;
+use Scalar::Util qw(blessed);
+
+use C4::Members;
+use C4::Letters;
+use Koha::Borrowers;
+
+use base qw(t::lib::TestObjects::ObjectFactory);
+
+use Koha::Exception::ObjectExists;
+
+sub new {
+    my ($class) = @_;
+
+    my $self = {};
+    bless($self, $class);
+    return $self;
+}
+
+sub getDefaultHashKey {
+    return 'from_address';
+}
+sub getObjectType {
+    return 'HASH';
+}
+
+=head createTestGroup( $data [, $hashKey, $testContexts...] )
+@OVERLOADED
+
+    MessageQueueFactory creates a new message into message_queue table with 'pending'
+    status. After testing, all messages created by the MessageQueueFactory will be
+    deleted at tearDown.
+
+    my $messages = t::lib::TestObjects::MessageQueueFactory->createTestGroup([
+                        {letter => {
+                         title => "Test title",
+                         content => "Tessst content",
+                         },
+                         cardnumber => $borrowers->{'superuberadmin'}->cardnumber,
+                         message_transport_type => 'sms',
+                         from_address => 'test@unique.com',
+                         },
+                    ], undef, $testContext1, $testContext2, $testContext3);
+
+    #Do test stuff...
+
+    t::lib::TestObjects::ObjectFactory->tearDownTestContext($testContext1);
+    t::lib::TestObjects::ObjectFactory->tearDownTestContext($testContext2);
+    t::lib::TestObjects::ObjectFactory->tearDownTestContext($testContext3);
+
+See t::lib::TestObjects::ObjectFactory for more documentation
+=cut
+
+sub handleTestObject {
+    my ($class, $notice, $stashes) = @_;
+
+    my $borrower = Koha::Borrowers->cast($notice->{cardnumber});
+
+    my $message_id = C4::Letters::EnqueueLetter({
+        letter                 => $notice->{letter},
+        borrowernumber         => $borrower->borrowernumber,
+        message_transport_type => $notice->{message_transport_type},
+        to_address             => $notice->{to_address},
+        from_address           => $notice->{from_address},
+    });
+
+    $notice->{message_id} = $message_id;
+
+    return $notice;
+}
+
+=head validateAndPopulateDefaultValues
+@OVERLOAD
+
+Validates given Object parameters and makes sure that critical fields are given
+and populates defaults for missing values.
+=cut
+
+sub validateAndPopulateDefaultValues {
+    my ($class, $object, $hashKey) = @_;
+    $class->SUPER::validateAndPopulateDefaultValues($object, $hashKey);
+
+    unless ($object->{cardnumber}) {
+        Koha::Exception::BadParameter->throw(error => __PACKAGE__."->createTestGroup():> 'cardnumber' is a mandatory parameter!");
+    }
+    unless ($object->{from_address}) {
+        Koha::Exception::BadParameter->throw(error => __PACKAGE__."->createTestGroup():> 'from_address' is a mandatory parameter!");
+    }
+    $object->{to_address} = 'nobody@example.com' unless defined $object->{to_address};
+    $object->{message_transport_type} = 'email' unless defined $object->{message_transport_type};
+    $object->{letter} = {
+        title => "Example message title",
+        content => "Example message content",
+        'content-type' => "Example message content type",
+    } unless defined $object->{letter};
+    $object->{letter}->{title} = "Example message title" unless defined $object->{letter}->{title};
+    $object->{letter}->{content} = "Example message content" unless defined $object->{letter}->{content};
+    $object->{letter}->{'content-type'} = "Example message content type" unless defined $object->{letter}->{'content-type'};
+}
+
+=head deleteTestGroup
+@OVERLOADED
+
+    my $records = createTestGroup();
+    ##Do funky stuff
+    deleteTestGroup($prefs);
+
+Removes the given test group from the DB.
+
+=cut
+
+sub deleteTestGroup {
+    my ($class, $messages) = @_;
+
+    my $schema = Koha::Database->new_schema();
+    while( my ($key, $msg) = each %$messages) {
+        $schema->resultset('MessageQueue')->find({"message_id" => $msg->{message_id}})->delete();
+    }
+}
+
+sub _deleteTestGroupFromIdentifiers {
+    my ($self, $testGroupIdentifiers) = @_;
+
+    my $schema = Koha::Database->new_schema();
+    foreach my $key (@$testGroupIdentifiers) {
+        $schema->resultset('MessageQueue')->find({"from_address" => $key})->delete();
+    }
+}
+
+
+1;
diff --git a/t/lib/TestObjects/ObjectFactory.pm b/t/lib/TestObjects/ObjectFactory.pm
index e4f6441..aac70df 100644
--- a/t/lib/TestObjects/ObjectFactory.pm
+++ b/t/lib/TestObjects/ObjectFactory.pm
@@ -181,6 +181,11 @@ sub tearDownTestContext {
         t::lib::TestObjects::SystemPreferenceFactory->deleteTestGroup($stash->{systempreference});
         delete $stash->{systempreference};
     }
+    if ($stash->{messageQueue}) {
+        require t::lib::TestObjects::MessageQueueFactory;
+        t::lib::TestObjects::MessageQueueFactory->deleteTestGroup($stash->{messageQueue});
+        delete $stash->{messageQueue};
+    }
 }
 
 =head getHashKey
diff --git a/t/lib/TestObjects/objectFactories.t b/t/lib/TestObjects/objectFactories.t
index c6668b9..6582397 100644
--- a/t/lib/TestObjects/objectFactories.t
+++ b/t/lib/TestObjects/objectFactories.t
@@ -50,6 +50,8 @@ use Koha::Serial::Subscription::Numberpatterns;
 use Koha::Serial::Serials;
 use t::lib::TestObjects::SystemPreferenceFactory;
 use C4::Context;
+use t::lib::TestObjects::MessageQueueFactory;
+use C4::Letters;
 
 
 my $testContext = {}; #Gather all created Objects here so we can finally remove them all.
@@ -510,6 +512,54 @@ sub testSystemPreferenceFactory {
 
 
 
+########## MessageQueueFactory subtests ##########
+subtest 't::lib::TestObjects::MessageQueueFactory' => sub {
+    my $subtestContext = {};
+
+    my $messages = t::lib::TestObjects::MessageQueueFactory->createTestGroup([
+            {letter => {
+                title => "The quick brown fox",
+                content => "Jumps over the lazy dog.",
+                },
+             cardnumber => '11A001',
+             message_transport_type => 'sms',
+             from_address => '11A001@example.com',
+            },
+        ], undef, $subtestContext);
+
+    # check that the message exists in queue
+    my $queued_messages = C4::Letters->_get_unsent_messages();
+
+    my $found_testMessage = 0;
+    foreach my $message (@$queued_messages){
+        if ($message->{from_address} eq '11A001@example.com'){
+            $found_testMessage = 1;
+            last;
+        }
+    }
+
+    ok($found_testMessage, 'MessageQueue \'11A001@example.com\', message_queue match.');
+
+    # delete the queued message
+    t::lib::TestObjects::MessageQueueFactory->deleteTestGroup($messages);
+
+    # confirm the deletion
+    $queued_messages = C4::Letters->_get_unsent_messages();
+
+    $found_testMessage = 0;
+    foreach my $message (@$queued_messages){
+        if ($message->{from_address} eq '11A001@example.com'){
+            $found_testMessage = 1;
+            last;
+        }
+    }
+
+    is($found_testMessage, 0, 'MessageQueue \'11A001@example.com\', deleted.');
+
+};
+
+
+
 ########## Global test context subtests ##########
 subtest 't::lib::TestObjects::ObjectFactory clearing global test context' => \&testGlobalSubtestContext;
 sub testGlobalSubtestContext {
-- 
1.9.1