From 4f584c36fa9e3d392b1c3740d66f8a41d0447e84 Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Tue, 5 Apr 2022 00:30:59 +0200 Subject: [PATCH] Bug 30360: Add methods for dealing with the JSON payload This patch adds high-level methods to handle the JSON payload (de)serialization as needed. This allows devs implementing background jobs to abstract themselves from the internals of the jobs handling. To test: 1. Apply this patch 2. Run: $ kshell k$ prove t/db_dependent/Koha/BackgroundJob.t => SUCCESS: Tests pass! 3. Sign off :-D Signed-off-by: Tomas Cohen Arazi Signed-off-by: David Nind Signed-off-by: Martin Renvoize --- Koha/BackgroundJob.pm | 28 ++++++++++++++++++++++++++++ t/db_dependent/Koha/BackgroundJob.t | 19 +++++++++++++++++-- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/Koha/BackgroundJob.pm b/Koha/BackgroundJob.pm index b6801cdf95..833d6d82a7 100644 --- a/Koha/BackgroundJob.pm +++ b/Koha/BackgroundJob.pm @@ -234,6 +234,34 @@ sub finish { )->store; } +=head3 decoded_data + + my $job_data = $self->decoded_data; + +Returns the decoded JSON contents from $self->data. + +=cut + +sub decoded_data { + my ($self) = @_; + + return decode_json($self->data); +} + +=head3 set_encoded_data + + $self->set_encoded_data( $data ); + +Serializes I<$data> as a JSON string and sets the I attribute with it. + +=cut + +sub set_encoded_data { + my ( $self, $data ) = @_; + + return $self->data( encode_json($data) ); +} + =head3 job_type Return the job type of the job. Must be a string. diff --git a/t/db_dependent/Koha/BackgroundJob.t b/t/db_dependent/Koha/BackgroundJob.t index 4801c68628..0cdaa2f93c 100755 --- a/t/db_dependent/Koha/BackgroundJob.t +++ b/t/db_dependent/Koha/BackgroundJob.t @@ -17,14 +17,14 @@ use Modern::Perl; -use Test::More tests => 3; +use Test::More tests => 4; use Test::Exception; use Koha::Database; use Koha::BackgroundJobs; use Koha::BackgroundJob::BatchUpdateItem; -use JSON qw( decode_json ); +use JSON qw( decode_json encode_json ); use t::lib::Mocks; use t::lib::TestBuilder; @@ -152,3 +152,18 @@ subtest 'start(), step() and finish() tests' => sub { $schema->storage->txn_rollback; }; + +subtest 'decoded_data() and set_encoded_data() tests' => sub { + + plan tests => 3; + + my $job = Koha::BackgroundJob::BatchUpdateItem->new->set_encoded_data( undef ); + is( $job->decoded_data, undef ); + + my $data = { some => 'data' }; + + $job->set_encoded_data( $data ); + + is_deeply( decode_json($job->data), $data ); + is_deeply( $job->decoded_data, $data ); +}; -- 2.20.1