Bug 16176: Fix a test about OpenLibrarySearch
[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 => 549;
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 verif_systempreferences_values( $report, 0 );
154
155 #mock with values
156 mocking_systempreferences_to_a_set_value(1);
157
158 $report = C4::UsageStats->BuildReport();
159 isa_ok( $report,                      'HASH', '$report is a HASH' );
160 isa_ok( $report->{systempreferences}, 'HASH', '$report->{systempreferences} is a HASH' );
161 verif_systempreferences_values( $report, 1 );
162
163 #Test if unwanted syspref are not sent
164 is( $report->{systempreferences}->{useDischarge}, undef, 'useDischarge should not be shared');
165 is( $report->{systempreferences}->{OpacUserJS},   undef, 'OpacUserJS   should not be shared');
166
167 # ---------- Testing ReportToCommunity ----------
168
169 # ---------- Testing _count ---------------------
170 my $query = '
171   SELECT count(*)
172   FROM   borrowers
173   ';
174 my $count = $dbh->selectrow_array($query);
175
176 my $nb_fields = C4::UsageStats::_count('borrowers');
177 is( $nb_fields, $count, "_count return the good number of fields" );
178
179 #################################################
180 #             Subs
181 #################################################
182
183 # Adding :
184 # 3 borrowers
185 # 4 biblio
186 # 3 biblio items
187 # 3 items
188 # 2 auth_header
189 # 1 old_issues
190 # 1 old_reserves
191 # 1 subscription
192 # 1 aqorders
193 sub construct_objects_needed {
194
195     # ---------- 3 borrowers  ---------------------
196     my $surname1     = 'Borrower 1';
197     my $surname2     = 'Borrower 2';
198     my $surname3     = 'Borrower 3';
199     my $firstname1   = 'firstname 1';
200     my $firstname2   = 'firstname 2';
201     my $firstname3   = 'firstname 3';
202     my $cardnumber1  = 'test_card1';
203     my $cardnumber2  = 'test_card2';
204     my $cardnumber3  = 'test_card3';
205     my $categorycode = Koha::Database->new()->schema()->resultset('Category')->first()->categorycode();
206     my $branchcode   = Koha::Database->new()->schema()->resultset('Branch')->first()->branchcode();
207
208     my $query = '
209     INSERT INTO borrowers
210       (surname, firstname, cardnumber, branchcode, categorycode)
211     VALUES (?,?,?,?,?)';
212     my $insert_sth = $dbh->prepare($query);
213     $insert_sth->execute( $surname1, $firstname1, $cardnumber1, $branchcode, $categorycode );
214     my $borrowernumber1 = $dbh->last_insert_id( undef, undef, 'borrowers', undef );
215     $insert_sth->execute( $surname2, $firstname2, $cardnumber2, $branchcode, $categorycode );
216     my $borrowernumber2 = $dbh->last_insert_id( undef, undef, 'borrowers', undef );
217     $insert_sth->execute( $surname3, $firstname3, $cardnumber3, $branchcode, $categorycode );
218     my $borrowernumber3 = $dbh->last_insert_id( undef, undef, 'borrowers', undef );
219
220     # ---------- 3 biblios -----------------------
221     my $title1  = 'Title 1';
222     my $title2  = 'Title 2';
223     my $title3  = 'Title 3';
224     my $author1 = 'Author 1';
225     my $author2 = 'Author 2';
226     my $author3 = 'Author 3';
227
228     $query = '
229     INSERT INTO biblio
230       (title, author)
231     VALUES (?,?)';
232     $insert_sth = $dbh->prepare($query);
233     $insert_sth->execute( $title1, $author1 );
234     my $biblionumber1 = $dbh->last_insert_id( undef, undef, 'biblio', undef );
235     $insert_sth->execute( $title2, undef );
236     my $biblionumber2 = $dbh->last_insert_id( undef, undef, 'biblio', undef );
237     $insert_sth->execute( $title3, $author3 );
238     my $biblionumber3 = $dbh->last_insert_id( undef, undef, 'biblio', undef );
239
240     # ---------- 3 biblio items  -------------------------
241     $query = '
242     INSERT INTO biblioitems
243       (biblionumber, itemtype, marcxml)
244     VALUES (?,?,?)';
245     $insert_sth = $dbh->prepare($query);
246     $insert_sth->execute( $biblionumber1, 'Book', '' );
247     my $biblioitemnumber1 = $dbh->last_insert_id( undef, undef, 'biblioitems', undef );
248     $insert_sth->execute( $biblionumber2, 'Music', '' );
249     my $biblioitemnumber2 = $dbh->last_insert_id( undef, undef, 'biblioitems', undef );
250     $insert_sth->execute( $biblionumber3, 'Book', '' );
251     my $biblioitemnumber3 = $dbh->last_insert_id( undef, undef, 'biblioitems', undef );
252
253     # ---------- 3 items  -------------------------
254     my $barcode1 = '111111';
255     my $barcode2 = '222222';
256     my $barcode3 = '333333';
257
258     $query = '
259     INSERT INTO items
260       (biblionumber, biblioitemnumber, barcode, itype)
261     VALUES (?,?,?,?)';
262     $insert_sth = $dbh->prepare($query);
263     $insert_sth->execute( $biblionumber1, $biblioitemnumber1, $barcode1, 'Book' );
264     my $item_number1 = $dbh->last_insert_id( undef, undef, 'items', undef );
265     $insert_sth->execute( $biblionumber2, $biblioitemnumber2, $barcode2, 'Music' );
266     my $item_number2 = $dbh->last_insert_id( undef, undef, 'items', undef );
267     $insert_sth->execute( $biblionumber3, $biblioitemnumber3, $barcode3, 'Book' );
268     my $item_number3 = $dbh->last_insert_id( undef, undef, 'items', undef );
269
270     # ---------- Add 2 auth_header
271     $query = '
272     INSERT INTO auth_header
273       (authtypecode)
274     VALUES (?)';
275     $insert_sth = $dbh->prepare($query);
276     $insert_sth->execute('authtypecode1');
277     my $authid1 = $dbh->last_insert_id( undef, undef, 'auth_header', undef );
278     $insert_sth->execute('authtypecode2');
279     my $authid2 = $dbh->last_insert_id( undef, undef, 'auth_header', undef );
280
281     # ---------- Add 1 old_issues
282     $query = '
283     INSERT INTO old_issues
284       (borrowernumber, branchcode, itemnumber)
285     VALUES (?,?,?)';
286     $insert_sth = $dbh->prepare($query);
287     $insert_sth->execute( $borrowernumber1, $branchcode, $item_number1 );
288     my $issue_id1 = $dbh->last_insert_id( undef, undef, 'old_issues', undef );
289
290     # ---------- Add 1 old_reserves
291     AddReserve( $branchcode, $borrowernumber1, $biblionumber1, '', 1, undef, undef, '', 'Title', undef, undef );
292     my $reserves1   = GetReservesFromBiblionumber( { biblionumber => $biblionumber1 } );
293     my $reserve_id1 = $reserves1->[0]->{reserve_id};
294     my $reserve1    = CancelReserve( { reserve_id => $reserve_id1 } );
295
296     # ---------- Add 1 aqbudgets
297     $query = '
298     INSERT INTO aqbudgets
299       (budget_amount)
300     VALUES (?)';
301     $insert_sth = $dbh->prepare($query);
302     $insert_sth->execute("20.0");
303     my $aqbudgets1 = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
304
305     # ---------- Add 1 aqorders
306     $query = '
307     INSERT INTO aqorders
308       (budget_id, basketno, biblionumber, invoiceid, subscriptionid)
309     VALUES (?,?,?,?,?)';
310     $insert_sth = $dbh->prepare($query);
311     $insert_sth->execute( $aqbudgets1, undef, undef, undef, undef );
312     my $aqorders1 = $dbh->last_insert_id( undef, undef, 'aqorders', undef );
313
314     # --------- Add 1 subscription
315     $query = '
316     INSERT INTO subscription
317       (biblionumber)
318     VALUES (?)';
319     $insert_sth = $dbh->prepare($query);
320     $insert_sth->execute($biblionumber1);
321     my $subscription1 = $dbh->last_insert_id( undef, undef, 'subscription', undef );
322
323 }
324
325 #Change systempreferences values to $set_value
326 sub mocking_systempreferences_to_a_set_value {
327     my $set_value = shift;
328
329     foreach (
330         qw/
331         AcqCreateItem
332         AcqWarnOnDuplicateInvoice
333         AcqViewBaskets
334         BasketConfirmations
335         OrderPdfFormat
336         casAuthentication
337         casLogout
338         AllowPKIAuth
339         DebugLevel
340         delimiter
341         noItemTypeImages
342         virtualshelves
343         AutoLocation
344         IndependentBranches
345         SessionStorage
346         Persona
347         AuthDisplayHierarchy
348         AutoCreateAuthorities
349         BiblioAddsAuthorities
350         dontmerge
351         UseAuthoritiesForTracings
352         CatalogModuleRelink
353         hide_marc
354         IntranetBiblioDefaultView
355         LabelMARCView
356         OpacSuppression
357         SeparateHoldings
358         UseControlNumber
359         advancedMARCeditor
360         DefaultClassificationSource
361         EasyAnalyticalRecords
362         autoBarcode
363         item-level_itypes
364         marcflavour
365         PrefillItem
366         z3950NormalizeAuthor
367         SpineLabelAutoPrint
368         SpineLabelShowPrintOnBibDetails
369         BlockReturnOfWithdrawnItems
370         CalculateFinesOnReturn
371         AgeRestrictionOverride
372         AllFinesNeedOverride
373         AllowFineOverride
374         AllowItemsOnHoldCheckout
375         AllowNotForLoanOverride
376         AllowRenewalLimitOverride
377         AllowReturnToBranch
378         AllowTooManyOverride
379         AutomaticItemReturn
380         AutoRemoveOverduesRestrictions
381         CircControl
382         HomeOrHoldingBranch
383         HomeOrHoldingBranchReturn
384         InProcessingToShelvingCart
385         IssueLostItem
386         IssuingInProcess
387         ManInvInNoissuesCharge
388         OverduesBlockCirc
389         RenewalPeriodBase
390         RenewalSendNotice
391         RentalsInNoissuesCharge
392         ReturnBeforeExpiry
393         ReturnToShelvingCart
394         TransfersMaxDaysWarning
395         UseBranchTransferLimits
396         useDaysMode
397         UseTransportCostMatrix
398         UseCourseReserves
399         finesCalendar
400         FinesIncludeGracePeriod
401         finesMode
402         RefundLostItemFeeOnReturn
403         WhenLostChargeReplacementFee
404         WhenLostForgiveFine
405         AllowHoldDateInFuture
406         AllowHoldPolicyOverride
407         AllowHoldsOnDamagedItems
408         AllowHoldsOnPatronsPossessions
409         AutoResumeSuspendedHolds
410         canreservefromotherbranches
411         decreaseLoanHighHolds
412         DisplayMultiPlaceHold
413         emailLibrarianWhenHoldIsPlaced
414         ExpireReservesMaxPickUpDelay
415         OPACAllowHoldDateInFuture
416         OPACAllowUserToChooseBranch
417         ReservesControlBranch
418         ReservesNeedReturns
419         SuspendHoldsIntranet
420         SuspendHoldsOpac
421         TransferWhenCancelAllWaitingHolds
422         AllowAllMessageDeletion
423         AllowOfflineCirculation
424         CircAutocompl
425         CircAutoPrintQuickSlip
426         DisplayClearScreenButton
427         FilterBeforeOverdueReport
428         FineNotifyAtCheckin
429         itemBarcodeFallbackSearch
430         itemBarcodeInputFilter
431         previousIssuesDefaultSortOrder
432         RecordLocalUseOnReturn
433         soundon
434         SpecifyDueDate
435         todaysIssuesDefaultSortOrder
436         UpdateTotalIssuesOnCirc
437         UseTablesortForCirc
438         WaitingNotifyAtCheckin
439         AllowSelfCheckReturns
440         AutoSelfCheckAllowed
441         FRBRizeEditions
442         OPACFRBRizeEditions
443         AmazonCoverImages
444         OPACAmazonCoverImages
445         Babeltheque
446         BakerTaylorEnabled
447         GoogleJackets
448         HTML5MediaEnabled
449         IDreamBooksReadometer
450         IDreamBooksResults
451         IDreamBooksReviews
452         LibraryThingForLibrariesEnabled
453         LocalCoverImages
454         OPACLocalCoverImages
455         NovelistSelectEnabled
456         XISBN
457         OpenLibraryCovers
458         OpenLibrarySearch
459         UseKohaPlugins
460         SyndeticsEnabled
461         TagsEnabled
462         CalendarFirstDayOfWeek
463         opaclanguagesdisplay
464         AuthoritiesLog
465         BorrowersLog
466         CataloguingLog
467         FinesLog
468         IssueLog
469         LetterLog
470         ReturnLog
471         SubscriptionLog
472         AuthorisedValueImages
473         BiblioDefaultView
474         COinSinOPACResults
475         DisplayOPACiconsXSLT
476         hidelostitems
477         HighlightOwnItemsOnOPAC
478         OpacAddMastheadLibraryPulldown
479         OPACDisplay856uAsImage
480         OpacHighlightedWords
481         OpacKohaUrl
482         OpacMaintenance
483         OpacPublic
484         OpacSeparateHoldings
485         OPACShowBarcode
486         OPACShowCheckoutName
487         OpacShowFiltersPulldownMobile
488         OPACShowHoldQueueDetails
489         OpacShowLibrariesPulldownMobile
490         OpacShowRecentComments
491         OPACShowUnusedAuthorities
492         OpacStarRatings
493         opacthemes
494         OPACURLOpenInNewWindow
495         OpacAuthorities
496         opacbookbag
497         OpacBrowser
498         OpacBrowseResults
499         OpacCloud
500         OPACFinesTab
501         OpacHoldNotes
502         OpacItemLocation
503         OpacPasswordChange
504         OPACPatronDetails
505         OPACpatronimages
506         OPACPopupAuthorsSearch
507         OpacTopissue
508         opacuserlogin
509         QuoteOfTheDay
510         RequestOnOpac
511         reviewson
512         ShowReviewer
513         ShowReviewerPhoto
514         SocialNetworks
515         suggestion
516         AllowPurchaseSuggestionBranchChoice
517         OpacAllowPublicListCreation
518         OpacAllowSharingPrivateLists
519         OpacRenewalAllowed
520         OpacRenewalBranch
521         OPACViewOthersSuggestions
522         SearchMyLibraryFirst
523         singleBranchMode
524         AnonSuggestions
525         EnableOpacSearchHistory
526         OPACPrivacy
527         opacreadinghistory
528         TrackClicks
529         PatronSelfRegistration
530         OPACShelfBrowser
531         AutoEmailOpacUser
532         AutoEmailPrimaryAddress
533         autoMemberNum
534         BorrowerRenewalPeriodBase
535         checkdigit
536         EnableBorrowerFiles
537         EnhancedMessagingPreferences
538         ExtendedPatronAttributes
539         intranetreadinghistory
540         memberofinstitution
541         patronimages
542         TalkingTechItivaPhoneNotification
543         uppercasesurnames
544         IncludeSeeFromInSearches
545         OpacGroupResults
546         QueryAutoTruncate
547         QueryFuzzy
548         QueryStemming
549         QueryWeightFields
550         TraceCompleteSubfields
551         TraceSubjectSubdivisions
552         UseICU
553         UseQueryParser
554         defaultSortField
555         displayFacetCount
556         OPACdefaultSortField
557         OPACItemsResultsDisplay
558         expandedSearchOption
559         IntranetNumbersPreferPhrase
560         OPACNumbersPreferPhrase
561         opacSerialDefaultTab
562         RenewSerialAddsSuggestion
563         RoutingListAddReserves
564         RoutingSerials
565         SubscriptionHistory
566         Display856uAsImage
567         DisplayIconsXSLT
568         StaffAuthorisedValueImages
569         template
570         yuipath
571         HidePatronName
572         intranetbookbag
573         StaffDetailItemSelection
574         viewISBD
575         viewLabeledMARC
576         viewMARC
577         ILS-DI
578         OAI-PMH
579         version
580         AudioAlerts
581         /
582       ) {
583         t::lib::Mocks::mock_preference( $_, $set_value );
584     }
585 }
586
587 #Test if all systempreferences are at $value_to_test
588 sub verif_systempreferences_values {
589     my ( $report, $value_to_test ) = @_;
590
591     foreach my $key ( keys %{$report->{systempreferences}} ) {
592         is( $report->{systempreferences}->{$key}, $value_to_test, "\$report->{systempreferences}->{$key} = $value_to_test" );
593     }
594 }
595
596 $dbh->rollback;