Bug 14097 - Correct noise under Debian
[koha.git] / t / db_dependent / UsageStats.t
1 # Copyright 2015 BibLibre
2 #
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, see <http://www.gnu.org/licenses>.
16
17 use Modern::Perl;
18 use Test::More tests => 551;
19 use t::lib::Mocks qw(mock_preference);
20 use POSIX qw(strftime);
21
22 BEGIN {
23     use_ok('C4::UsageStats');
24     use_ok('C4::Context');
25     use_ok('C4::Biblio');
26     use_ok( 'C4::AuthoritiesMarc', qw(AddAuthority) );
27     use_ok('C4::Reserves');
28     use_ok('MARC::Record');
29     use_ok('Koha::Acquisition::Order');
30 }
31
32 can_ok(
33     'C4::UsageStats', qw(
34       NeedUpdate
35       BuildReport
36       ReportToCommunity
37       _count )
38 );
39
40 my $dbh = C4::Context->dbh;
41 $dbh->{AutoCommit} = 0;
42 $dbh->{RaiseError} = 1;
43
44 $dbh->do('DELETE FROM issues');
45 $dbh->do('DELETE FROM biblio');
46 $dbh->do('DELETE FROM items');
47 $dbh->do('DELETE FROM auth_header');
48 $dbh->do('DELETE FROM old_issues');
49 $dbh->do('DELETE FROM old_reserves');
50 $dbh->do('DELETE FROM borrowers');
51 $dbh->do('DELETE FROM aqorders');
52 $dbh->do('DELETE FROM subscription');
53
54 #################################################
55 #             Testing Subs
56 #################################################
57
58 # ---------- Testing NeedUpdate -----------------
59
60 #Mocking C4::Context->preference("UsageStatsLastUpdateTime") to 0
61 my $now = strftime( "%s", localtime );
62 t::lib::Mocks::mock_preference( "UsageStatsLastUpdateTime", 0 );
63
64 my $update = C4::UsageStats->NeedUpdate;
65 is( $update, 1, "There is no last update, update needed" );
66
67 #Mocking C4::Context->preference("UsageStatsLastUpdateTime") to now
68 $now = strftime( "%s", localtime );
69 t::lib::Mocks::mock_preference( "UsageStatsLastUpdateTime", $now );
70
71 $update = C4::UsageStats->NeedUpdate;
72 is( $update, 0, "Last update just be done, no update needed " );
73
74 # ---------- Testing BuildReport ----------------
75
76 #Test report->library -----------------
77 #mock to 0
78 t::lib::Mocks::mock_preference( "UsageStatsID",          0 );
79 t::lib::Mocks::mock_preference( "UsageStatsLibraryName", 0 );
80 t::lib::Mocks::mock_preference( "UsageStatsLibraryUrl",  0 );
81 t::lib::Mocks::mock_preference( "UsageStatsLibraryType", 0 );
82 t::lib::Mocks::mock_preference( "UsageStatsCountry",     0 );
83
84 my $report = C4::UsageStats->BuildReport();
85
86 isa_ok( $report,            'HASH', '$report is a HASH' );
87 isa_ok( $report->{library}, 'HASH', '$report->{library} is a HASH' );
88 is( scalar( keys %{$report->{library}} ), 5,  "There are 5 fields in $report->{library}" );
89 is( $report->{library}->{id},             0,  "UsageStatsID           is good" );
90 is( $report->{library}->{name},           '', "UsageStatsLibraryName  is good" );
91 is( $report->{library}->{url},            '', "UsageStatsLibraryUrl   is good" );
92 is( $report->{library}->{type},           '', "UsageStatsLibraryType  is good" );
93 is( $report->{library}->{country},        '', "UsageStatsCountry      is good" );
94
95 #mock with values
96 t::lib::Mocks::mock_preference( "UsageStatsID",          1 );
97 t::lib::Mocks::mock_preference( "UsageStatsLibraryName", 'NAME' );
98 t::lib::Mocks::mock_preference( "UsageStatsLibraryUrl",  'URL' );
99 t::lib::Mocks::mock_preference( "UsageStatsLibraryType", 'TYPE' );
100 t::lib::Mocks::mock_preference( "UsageStatsCountry",     'COUNTRY' );
101
102 $report = C4::UsageStats->BuildReport();
103
104 isa_ok( $report,            'HASH', '$report is a HASH' );
105 isa_ok( $report->{library}, 'HASH', '$report->{library} is a HASH' );
106 is( scalar( keys %{$report->{library}} ), 5,         "There are 5 fields in $report->{library}" );
107 is( $report->{library}->{id},             1,         "UsageStatsID            is good" );
108 is( $report->{library}->{name},           'NAME',    "UsageStatsLibraryName   is good" );
109 is( $report->{library}->{url},            'URL',     "UsageStatsLibraryUrl    is good" );
110 is( $report->{library}->{type},           'TYPE',    "UsageStatsLibraryType   is good" );
111 is( $report->{library}->{country},        'COUNTRY', "UsageStatsCountry       is good" );
112
113 #Test report->volumetry ---------------
114 #with original values
115 $report = C4::UsageStats->BuildReport();
116
117 isa_ok( $report,              'HASH', '$report is a HASH' );
118 isa_ok( $report->{volumetry}, 'HASH', '$report->{volumetry} is a HASH' );
119 is( scalar( keys %{$report->{volumetry}} ), 8, "There are 8 fields in $report->{volumetry}" );
120 is( $report->{volumetry}->{biblio},         0, "There is no biblio" );
121 is( $report->{volumetry}->{items},          0, "There is no items" );
122 is( $report->{volumetry}->{auth_header},    0, "There is no auth_header" );
123 is( $report->{volumetry}->{old_issues},     0, "There is no old_issues" );
124 is( $report->{volumetry}->{old_reserves},   0, "There is no old_reserves" );
125 is( $report->{volumetry}->{borrowers},      0, "There is no borrowers" );
126 is( $report->{volumetry}->{aqorders},       0, "There is no aqorders" );
127 is( $report->{volumetry}->{subscription},   0, "There is no subscription" );
128
129 #after adding objects
130 construct_objects_needed();
131
132 $report = C4::UsageStats->BuildReport();
133
134 isa_ok( $report,              'HASH', '$report is a HASH' );
135 isa_ok( $report->{volumetry}, 'HASH', '$report->{volumetry} is a HASH' );
136 is( scalar( keys %{$report->{volumetry}} ), 8, "There are 8 fields in $report->{volumetry}" );
137 is( $report->{volumetry}->{biblio},         3, "There are 3 biblio" );
138 is( $report->{volumetry}->{items},          3, "There are 3 items" );
139 is( $report->{volumetry}->{auth_header},    2, "There are 2 auth_header" );
140 is( $report->{volumetry}->{old_issues},     1, "There is  1 old_issues" );
141 is( $report->{volumetry}->{old_reserves},   1, "There is  1 old_reserves" );
142 is( $report->{volumetry}->{borrowers},      3, "There are 3 borrowers" );
143 is( $report->{volumetry}->{aqorders},       1, "There is  1 aqorders" );
144 is( $report->{volumetry}->{subscription},   1, "There is  1 subscription" );
145
146 #Test report->systempreferences -------
147 #mock to 0
148 mocking_systempreferences_to_a_set_value(0);
149
150 $report = C4::UsageStats->BuildReport();
151 isa_ok( $report,                      'HASH', '$report is a HASH' );
152 isa_ok( $report->{systempreferences}, 'HASH', '$report->{systempreferences} is a HASH' );
153 is( scalar( keys %{$report->{systempreferences}} ), 248, "There are 248 fields in $report->{systempreferences}" );
154 verif_systempreferences_values( $report, 0 );
155
156 #mock with values
157 mocking_systempreferences_to_a_set_value(1);
158
159 $report = C4::UsageStats->BuildReport();
160 isa_ok( $report,                      'HASH', '$report is a HASH' );
161 isa_ok( $report->{systempreferences}, 'HASH', '$report->{systempreferences} is a HASH' );
162 is( scalar( keys %{$report->{systempreferences}} ), 248, "There are 248 fields in $report->{systempreferences}" );
163 verif_systempreferences_values( $report, 1 );
164
165 # ---------- Testing ReportToCommunity ----------
166
167 # ---------- Testing _count ---------------------
168 my $query = '
169   SELECT count(*)
170   FROM   borrowers
171   ';
172 my $count = $dbh->selectrow_array($query);
173
174 my $nb_fields = C4::UsageStats::_count('borrowers');
175 is( $nb_fields, $count, "_count return the good number of fields" );
176
177 #################################################
178 #             Subs
179 #################################################
180
181 # Adding :
182 # 3 borrowers
183 # 4 biblio
184 # 3 biblio items
185 # 3 items
186 # 2 auth_header
187 # 1 old_issues
188 # 1 old_reserves
189 # 1 subscription
190 # 1 aqorders
191 sub construct_objects_needed {
192
193     # ---------- 3 borrowers  ---------------------
194     my $surname1     = 'Borrower 1';
195     my $surname2     = 'Borrower 2';
196     my $surname3     = 'Borrower 3';
197     my $firstname1   = 'firstname 1';
198     my $firstname2   = 'firstname 2';
199     my $firstname3   = 'firstname 3';
200     my $cardnumber1  = 'test_card1';
201     my $cardnumber2  = 'test_card2';
202     my $cardnumber3  = 'test_card3';
203     my $categorycode = Koha::Database->new()->schema()->resultset('Category')->first()->categorycode();
204     my $branchcode   = Koha::Database->new()->schema()->resultset('Branch')->first()->branchcode();
205
206     my $query = '
207     INSERT INTO borrowers
208       (surname, firstname, cardnumber, branchcode, categorycode)
209     VALUES (?,?,?,?,?)';
210     my $insert_sth = $dbh->prepare($query);
211     $insert_sth->execute( $surname1, $firstname1, $cardnumber1, $branchcode, $categorycode );
212     my $borrowernumber1 = $dbh->last_insert_id( undef, undef, 'borrowers', undef );
213     $insert_sth->execute( $surname2, $firstname2, $cardnumber2, $branchcode, $categorycode );
214     my $borrowernumber2 = $dbh->last_insert_id( undef, undef, 'borrowers', undef );
215     $insert_sth->execute( $surname3, $firstname3, $cardnumber3, $branchcode, $categorycode );
216     my $borrowernumber3 = $dbh->last_insert_id( undef, undef, 'borrowers', undef );
217
218     # ---------- 3 biblios -----------------------
219     my $title1  = 'Title 1';
220     my $title2  = 'Title 2';
221     my $title3  = 'Title 3';
222     my $author1 = 'Author 1';
223     my $author2 = 'Author 2';
224     my $author3 = 'Author 3';
225
226     $query = '
227     INSERT INTO biblio
228       (title, author)
229     VALUES (?,?)';
230     $insert_sth = $dbh->prepare($query);
231     $insert_sth->execute( $title1, $author1 );
232     my $biblionumber1 = $dbh->last_insert_id( undef, undef, 'biblio', undef );
233     $insert_sth->execute( $title2, undef );
234     my $biblionumber2 = $dbh->last_insert_id( undef, undef, 'biblio', undef );
235     $insert_sth->execute( $title3, $author3 );
236     my $biblionumber3 = $dbh->last_insert_id( undef, undef, 'biblio', undef );
237
238     # ---------- 3 biblio items  -------------------------
239     $query = '
240     INSERT INTO biblioitems
241       (biblionumber, itemtype, marcxml)
242     VALUES (?,?,?)';
243     $insert_sth = $dbh->prepare($query);
244     $insert_sth->execute( $biblionumber1, 'Book', '' );
245     my $biblioitemnumber1 = $dbh->last_insert_id( undef, undef, 'biblioitems', undef );
246     $insert_sth->execute( $biblionumber2, 'Music', '' );
247     my $biblioitemnumber2 = $dbh->last_insert_id( undef, undef, 'biblioitems', undef );
248     $insert_sth->execute( $biblionumber3, 'Book', '' );
249     my $biblioitemnumber3 = $dbh->last_insert_id( undef, undef, 'biblioitems', undef );
250
251     # ---------- 3 items  -------------------------
252     my $barcode1 = '111111';
253     my $barcode2 = '222222';
254     my $barcode3 = '333333';
255
256     $query = '
257     INSERT INTO items
258       (biblionumber, biblioitemnumber, barcode, itype)
259     VALUES (?,?,?,?)';
260     $insert_sth = $dbh->prepare($query);
261     $insert_sth->execute( $biblionumber1, $biblioitemnumber1, $barcode1, 'Book' );
262     my $item_number1 = $dbh->last_insert_id( undef, undef, 'items', undef );
263     $insert_sth->execute( $biblionumber2, $biblioitemnumber2, $barcode2, 'Music' );
264     my $item_number2 = $dbh->last_insert_id( undef, undef, 'items', undef );
265     $insert_sth->execute( $biblionumber3, $biblioitemnumber3, $barcode3, 'Book' );
266     my $item_number3 = $dbh->last_insert_id( undef, undef, 'items', undef );
267
268     # ---------- Add 2 auth_header
269     $query = '
270     INSERT INTO auth_header
271       (authtypecode)
272     VALUES (?)';
273     $insert_sth = $dbh->prepare($query);
274     $insert_sth->execute('authtypecode1');
275     my $authid1 = $dbh->last_insert_id( undef, undef, 'auth_header', undef );
276     $insert_sth->execute('authtypecode2');
277     my $authid2 = $dbh->last_insert_id( undef, undef, 'auth_header', undef );
278
279     # ---------- Add 1 old_issues
280     $query = '
281     INSERT INTO old_issues
282       (borrowernumber, branchcode, itemnumber)
283     VALUES (?,?,?)';
284     $insert_sth = $dbh->prepare($query);
285     $insert_sth->execute( $borrowernumber1, $branchcode, $item_number1 );
286     my $issue_id1 = $dbh->last_insert_id( undef, undef, 'old_issues', undef );
287
288     # ---------- Add 1 old_reserves
289     AddReserve( $branchcode, $borrowernumber1, $biblionumber1, 'a', '', 1, undef, undef, '', 'Title', undef, undef );
290     my $reserves1   = GetReservesFromBiblionumber( { biblionumber => $biblionumber1 } );
291     my $reserve_id1 = $reserves1->[0]->{reserve_id};
292     my $reserve1    = CancelReserve( { reserve_id => $reserve_id1 } );
293
294     # ---------- Add 1 aqbudgets
295     $query = '
296     INSERT INTO aqbudgets
297       (budget_amount)
298     VALUES (?)';
299     $insert_sth = $dbh->prepare($query);
300     $insert_sth->execute("20.0");
301     my $aqbudgets1 = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
302
303     # ---------- Add 1 aqorders
304     $query = '
305     INSERT INTO aqorders
306       (budget_id, basketno, biblionumber, invoiceid, subscriptionid)
307     VALUES (?,?,?,?,?)';
308     $insert_sth = $dbh->prepare($query);
309     $insert_sth->execute( $aqbudgets1, undef, undef, undef, undef );
310     my $aqorders1 = $dbh->last_insert_id( undef, undef, 'aqorders', undef );
311
312     # --------- Add 1 subscription
313     $query = '
314     INSERT INTO subscription
315       (biblionumber)
316     VALUES (?)';
317     $insert_sth = $dbh->prepare($query);
318     $insert_sth->execute($biblionumber1);
319     my $subscription1 = $dbh->last_insert_id( undef, undef, 'subscription', undef );
320
321 }
322
323 #Change systempreferences values to $set_value
324 sub mocking_systempreferences_to_a_set_value {
325     my $set_value = shift;
326
327     foreach (
328         qw/
329         AcqCreateItem
330         AcqWarnOnDuplicateInvoice
331         AcqViewBaskets
332         BasketConfirmations
333         OrderPdfFormat
334         casAuthentication
335         casLogout
336         AllowPkiAuth
337         DebugLevel
338         delimiter
339         noItemTypeImages
340         virtualshelves
341         AutoLocation
342         IndependentBranches
343         SessionStorage
344         Persona
345         AuthDisplayHierarchy
346         AutoCreateAuthorities
347         BiblioAddsAuthorities
348         dontmerge
349         UseAuthoritiesForTracings
350         CatalogModuleRelink
351         hide_marc
352         IntranetBiblioDefaultView
353         LabelMARCView
354         OpacSuppression
355         SeparateHoldings
356         UseControlNumber
357         advancedMARCeditor
358         DefaultClassificationSource
359         EasyAnalyticalRecords
360         autoBarcode
361         item-level_itypes
362         marcflavour
363         PrefillItem
364         z3950NormalizeAuthor
365         SpineLabelAutoPrint
366         SpineLabelShowPrintOnBibDetails
367         BlockReturnOfWithdrawnItems
368         CalculateFinesOnReturn
369         AgeRestrictionOverride
370         AllFinesNeedOverride
371         AllowFineOverride
372         AllowItemsOnHoldCheckout
373         AllowNotForLoanOverride
374         AllowRenewalLimitOverride
375         AllowReturnToBranch
376         AllowTooManyOverride
377         AutomaticItemReturn
378         AutoRemoveOverduesRestrictions
379         CircControl
380         HomeOrHoldingBranch
381         HomeOrHoldingBranchReturn
382         InProcessingToShelvingCart
383         IssueLostItem
384         IssuingInProcess
385         ManInvInNoissuesCharge
386         OverduesBlockCirc
387         RenewalPeriodBase
388         RenewalSendNotice
389         RentalsInNoissuesCharge
390         ReturnBeforeExpiry
391         ReturnToShelvingCart
392         TransfersMaxDaysWarning
393         UseBranchTransferLimits
394         useDaysMode
395         UseTransportCostMatrix
396         UseCourseReserves
397         finesCalendar
398         FinesIncludeGracePeriod
399         finesMode
400         RefundLostItemFeeOnReturn
401         WhenLostChargeReplacementFee
402         WhenLostForgiveFine
403         AllowHoldDateInFuture
404         AllowHoldPolicyOverride
405         AllowHoldsOnDamagedItems
406         AllowHoldsOnPatronsPossessions
407         AutoResumeSuspendedHolds
408         canreservefromotherbranches
409         decreaseLoanHighHolds
410         DisplayMultiPlaceHold
411         emailLibrarianWhenHoldIsPlaced
412         ExpireReservesMaxPickUpDelay
413         OPACAllowHoldDateInFuture
414         OPACAllowUserToChooseBranch
415         ReservesControlBranch
416         ReservesNeedReturns
417         SuspendHoldsIntranet
418         SuspendHoldsOpac
419         TransferWhenCancelAllWaitingHolds
420         AllowAllMessageDeletion
421         AllowOfflineCirculation
422         CircAutocompl
423         CircAutoPrintQuickSlip
424         DisplayClearScreenButton
425         FilterBeforeOverdueReport
426         FineNotifyAtCheckin
427         itemBarcodeFallbackSearch
428         itemBarcodeInputFilter
429         previousIssuesDefaultSortOrder
430         RecordLocalUseOnReturn
431         soundon
432         SpecifyDueDate
433         todaysIssuesDefaultSortOrder
434         UpdateTotalIssuesOnCirc
435         UseTablesortForCirc
436         WaitingNotifyAtCheckin
437         AllowSelfCheckReturns
438         AutoSelfCheckAllowed
439         FRBRizeEditions
440         OPACFRBRizeEditions
441         AmazonCoverImages
442         OPACAmazonCoverImages
443         Babeltheque
444         BakerTaylorEnabled
445         GoogleJackets
446         HTML5MediaEnabled
447         IDreamBooksReadometer
448         IDreamBooksResults
449         IDreamBooksReviews
450         LibraryThingForLibrariesEnabled
451         LocalCoverImages
452         OPACLocalCoverImages
453         NovelistSelectEnabled
454         XISBN
455         OpenLibraryCovers
456         UseKohaPlugins
457         SyndeticsEnabled
458         TagsEnabled
459         CalendarFirstDayOfWeek
460         opaclanguagesdisplay
461         AuthoritiesLog
462         BorrowersLog
463         CataloguingLog
464         FinesLog
465         IssueLog
466         LetterLog
467         ReturnLog
468         SubscriptionLog
469         AuthorisedValueImages
470         BiblioDefaultView
471         COinSinOPACResults
472         DisplayOPACiconsXSLT
473         hidelostitems
474         HighlightOwnItemsOnOPAC
475         OpacAddMastheadLibraryPulldown
476         OPACDisplay856uAsImage
477         OpacHighlightedWords
478         OpacKohaUrl
479         OpacMaintenance
480         OpacPublic
481         OpacSeparateHoldings
482         OPACShowBarcode
483         OPACShowCheckoutName
484         OpacShowFiltersPulldownMobile
485         OPACShowHoldQueueDetails
486         OpacShowLibrariesPulldownMobile
487         OpacShowRecentComments
488         OPACShowUnusedAuthorities
489         OpacStarRatings
490         opacthemes
491         OPACURLOpenInNewWindow
492         OpacAuthorities
493         opacbookbag
494         OpacBrowser
495         OpacBrowseResults
496         OpacCloud
497         OPACFinesTab
498         OpacHoldNotes
499         OpacItemLocation
500         OpacPasswordChange
501         OPACPatronDetails
502         OPACpatronimages
503         OPACPopupAuthorsSearch
504         OpacTopissue
505         opacuserlogin
506         QuoteOfTheDay
507         RequestOnOpac
508         reviewson
509         ShowReviewer
510         ShowReviewerPhoto
511         SocialNetworks
512         suggestion
513         AllowPurchaseSuggestionBranchChoice
514         OpacAllowPublicListCreation
515         OpacAllowSharingPrivateLists
516         OpacRenewalAllowed
517         OpacRenewalBranch
518         OPACViewOthersSuggestions
519         SearchMyLibraryFirst
520         singleBranchMode
521         AnonSuggestions
522         EnableOpacSearchHistory
523         OPACPrivacy
524         opacreadinghistory
525         TrackClicks
526         PatronSelfRegistration
527         OPACShelfBrowser
528         AutoEmailOpacUser
529         AutoEmailPrimaryAddress
530         autoMemberNum
531         BorrowerRenewalPeriodBase
532         checkdigit
533         EnableBorrowerFiles
534         EnhancedMessagingPreferences
535         ExtendedPatronAttributes
536         intranetreadinghistory
537         memberofinstitution
538         patronimages
539         TalkingTechItivaPhoneNotification
540         uppercasesurnames
541         IncludeSeeFromInSearches
542         OpacGroupResults
543         QueryAutoTruncate
544         QueryFuzzy
545         QueryStemming
546         QueryWeightFields
547         TraceCompleteSubfields
548         TraceSubjectSubdivisions
549         UseICU
550         UseQueryParser
551         defaultSortField
552         displayFacetCount
553         OPACdefaultSortField
554         OPACItemsResultsDisplay
555         expandedSearchOption
556         IntranetNumbersPreferPhrase
557         OPACNumbersPreferPhrase
558         opacSerialDefaultTab
559         RenewSerialAddsSuggestion
560         RoutingListAddReserves
561         RoutingSerials
562         SubscriptionHistory
563         Display856uAsImage
564         DisplayIconsXSLT
565         StaffAuthorisedValueImages
566         template
567         yuipath
568         HidePatronName
569         intranetbookbag
570         StaffDetailItemSelection
571         viewISBD
572         viewLabeledMARC
573         viewMARC
574         ILS-DI
575         OAI-PMH
576         version
577         /
578       ) {
579         t::lib::Mocks::mock_preference( $_, $set_value );
580     }
581 }
582
583 #Test if all systempreferences are at $value_to_test
584 sub verif_systempreferences_values {
585     my ( $report, $value_to_test ) = @_;
586
587     foreach my $key ( keys %{$report->{systempreferences}} ) {
588         is( $report->{systempreferences}->{$key}, $value_to_test, "\$report->{systempreferences}->{$key} = $value_to_test" );
589     }
590 }
591
592 $dbh->rollback;