This repository was archived by the owner on Mar 28, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtesting.py
More file actions
1669 lines (1414 loc) · 56.4 KB
/
testing.py
File metadata and controls
1669 lines (1414 loc) · 56.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import inspect
import json
import logging
import os
import shutil
import tempfile
import time
import uuid
from datetime import timedelta
from pdb import set_trace
import mock
import pytest
from psycopg2.errors import UndefinedTable
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.orm.session import Session
from . import external_search
from .analytics import Analytics
from .classifier import Classifier
from .config import Configuration
from .coverage import (
BibliographicCoverageProvider,
CollectionCoverageProvider,
CoverageFailure,
IdentifierCoverageProvider,
WorkCoverageProvider,
)
from .external_search import (
ExternalSearchIndex,
MockExternalSearchIndex,
SearchIndexCoverageProvider,
)
from .lane import Lane
from .log import LogConfiguration
from .model import (
Base,
Classification,
Collection,
Complaint,
ConfigurationSetting,
Contributor,
CoverageRecord,
Credential,
CustomList,
DataSource,
DelegatedPatronIdentifier,
DeliveryMechanism,
Edition,
ExternalIntegration,
Genre,
Hyperlink,
Identifier,
IntegrationClient,
Library,
License,
LicensePool,
LicensePoolDeliveryMechanism,
Patron,
PresentationCalculationPolicy,
Representation,
Resource,
RightsStatus,
SessionManager,
Subject,
Work,
WorkCoverageRecord,
create,
get_one_or_create,
)
from .model.configuration import ExternalIntegrationLink
from .model.constants import MediaTypes
from .model.licensing import LicenseStatus
from .util.datetime_helpers import datetime_utc, utc_now
class LogCaptureHandler(logging.Handler):
"""A `logging.Handler` context manager that captures the messages
of emitted log records in the context of the specified `logger`.
"""
_level_names = logging._levelToName.values()
@staticmethod
def _normalize_level(level):
return level.lower()
LEVEL_NAMES = list(map(_normalize_level.__func__, _level_names))
def __init__(self, logger, *args, **kwargs):
"""Constructor.
:param logger: `logger` to which this handler will be added.
:param args: positional arguments to `logging.Handler.__init__`.
:param kwargs: keyword arguments to `logging.Handler.__init__`.
"""
self.logger = logger
self._records = {}
logging.Handler.__init__(self, *args, **kwargs)
def __enter__(self):
self.reset()
self.logger.addHandler(self)
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.logger.removeHandler(self)
def emit(self, record):
level = self._normalize_level(record.levelname)
if level not in self.LEVEL_NAMES:
message = "Unexpected log level: '%s'." % record.levelname
raise ValueError(message)
self._records[level].append(record.getMessage())
def reset(self):
"""Empty the message accumulators."""
self._records = {level: [] for level in self.LEVEL_NAMES}
def __getitem__(self, item):
if item in self.LEVEL_NAMES:
return self._records[item]
else:
message = "'%s' object has no attribute '%s'" % (
self.__class__.__name__,
item,
)
raise AttributeError(message)
def __getattr__(self, item):
return self.__getitem__(item)
class DatabaseTest(object):
engine = None
connection = None
@classmethod
def get_database_connection(cls):
url = Configuration.database_url()
engine, connection = SessionManager.initialize(url)
return engine, connection
@classmethod
def setup_class(cls):
# Initialize a temporary data directory.
cls.engine, cls.connection = cls.get_database_connection()
cls.old_data_dir = Configuration.data_directory
cls.tmp_data_dir = tempfile.mkdtemp(dir="/tmp")
Configuration.instance[Configuration.DATA_DIRECTORY] = cls.tmp_data_dir
# Avoid CannotLoadConfiguration errors related to CDN integrations.
Configuration.instance[Configuration.INTEGRATIONS] = Configuration.instance.get(
Configuration.INTEGRATIONS, {}
)
Configuration.instance[Configuration.INTEGRATIONS][ExternalIntegration.CDN] = {}
@classmethod
def teardown_class(cls):
# Destroy the database connection and engine.
cls.connection.close()
cls.engine.dispose()
if cls.tmp_data_dir.startswith("/tmp"):
logging.debug("Removing temporary directory %s" % cls.tmp_data_dir)
shutil.rmtree(cls.tmp_data_dir)
else:
logging.warn(
"Cowardly refusing to remove 'temporary' directory %s"
% cls.tmp_data_dir
)
Configuration.instance[Configuration.DATA_DIRECTORY] = cls.old_data_dir
@pytest.fixture(autouse=True)
def search_mock(self, request):
# Only setup the elasticsearch mock if the elasticsearch mark isn't set
elasticsearch_mark = request.node.get_closest_marker("elasticsearch")
if elasticsearch_mark is not None:
self.search_mock = None
else:
self.search_mock = mock.patch(
external_search.__name__ + ".ExternalSearchIndex",
MockExternalSearchIndex,
)
self.search_mock.start()
yield
if self.search_mock:
self.search_mock.stop()
def setup_method(self):
# Create a new connection to the database.
self._db = Session(self.connection)
self.transaction = self.connection.begin_nested()
# Start with a high number so it won't interfere with tests that search for an age or grade
self.counter = 2000
self.time_counter = datetime_utc(2014, 1, 1)
self.isbns = [
"9780674368279",
"0636920028468",
"9781936460236",
"9780316075978",
]
def teardown_method(self):
# Close the session.
self._db.close()
# Roll back all database changes that happened during this
# test, whether in the session that was just closed or some
# other session.
self.transaction.rollback()
# Reset the Analytics singleton between tests.
Analytics._reset_singleton_instance()
# Also roll back any record of those changes in the
# Configuration instance.
for key in [
Configuration.SITE_CONFIGURATION_LAST_UPDATE,
Configuration.LAST_CHECKED_FOR_SITE_CONFIGURATION_UPDATE,
]:
if key in Configuration.instance:
del Configuration.instance[key]
def time_eq(self, a, b):
"Assert that two times are *approximately* the same -- within 2 seconds."
if a < b:
delta = b - a
else:
delta = a - b
total_seconds = delta.total_seconds()
assert total_seconds < 2, "Delta was too large: %.2f seconds." % total_seconds
def shortDescription(self):
return None # Stop nosetests displaying docstrings instead of class names when verbosity level >= 2.
@property
def _id(self):
self.counter += 1
return self.counter
@property
def _str(self):
return str(self._id)
@property
def _time(self):
v = self.time_counter
self.time_counter = self.time_counter + timedelta(days=1)
return v
@property
def _isbn(self):
return self.isbns.pop()
@property
def _url(self):
return "http://foo.com/" + self._str
def _patron(self, external_identifier=None, library=None):
external_identifier = external_identifier or self._str
library = library or self._default_library
return get_one_or_create(
self._db, Patron, external_identifier=external_identifier, library=library
)[0]
def _contributor(self, sort_name=None, name=None, **kw_args):
name = sort_name or name or self._str
return get_one_or_create(self._db, Contributor, sort_name=str(name), **kw_args)
def _identifier(self, identifier_type=Identifier.GUTENBERG_ID, foreign_id=None):
if foreign_id:
id = foreign_id
else:
id = self._str
return Identifier.for_foreign_id(self._db, identifier_type, id)[0]
def _edition(
self,
data_source_name=DataSource.GUTENBERG,
identifier_type=Identifier.GUTENBERG_ID,
with_license_pool=False,
with_open_access_download=False,
title=None,
language="eng",
authors=None,
identifier_id=None,
series=None,
collection=None,
publication_date=None,
self_hosted=False,
unlimited_access=False,
):
id = identifier_id or self._str
source = DataSource.lookup(self._db, data_source_name)
wr = Edition.for_foreign_id(self._db, source, identifier_type, id)[0]
if not title:
title = self._str
wr.title = str(title)
wr.medium = Edition.BOOK_MEDIUM
if series:
wr.series = series
if language:
wr.language = language
if authors is None:
authors = self._str
if isinstance(authors, str):
authors = [authors]
if authors:
primary_author_name = str(authors[0])
contributor = wr.add_contributor(
primary_author_name, Contributor.PRIMARY_AUTHOR_ROLE
)
# add_contributor assumes authors[0] is a sort_name,
# but it may be a display name. If so, set that field as well.
if not contributor.display_name and "," not in primary_author_name:
contributor.display_name = primary_author_name
wr.author = primary_author_name
for author in authors[1:]:
wr.add_contributor(str(author), Contributor.AUTHOR_ROLE)
if publication_date:
wr.published = publication_date
if with_license_pool or with_open_access_download:
pool = self._licensepool(
wr,
data_source_name=data_source_name,
with_open_access_download=with_open_access_download,
collection=collection,
self_hosted=self_hosted,
unlimited_access=unlimited_access,
)
pool.set_presentation_edition()
return wr, pool
return wr
def _work(
self,
title=None,
authors=None,
genre=None,
language=None,
audience=None,
fiction=True,
with_license_pool=False,
with_open_access_download=False,
quality=0.5,
series=None,
presentation_edition=None,
collection=None,
data_source_name=None,
self_hosted=False,
unlimited_access=False,
):
"""Create a Work.
For performance reasons, this method does not generate OPDS
entries or calculate a presentation edition for the new
Work. Tests that rely on this information being present
should call _slow_work() instead, which takes more care to present
the sort of Work that would be created in a real environment.
"""
pools = []
if with_open_access_download:
with_license_pool = True
language = language or "eng"
title = str(title or self._str)
audience = audience or Classifier.AUDIENCE_ADULT
if audience == Classifier.AUDIENCE_CHILDREN and not data_source_name:
# TODO: This is necessary because Gutenberg's childrens books
# get filtered out at the moment.
data_source_name = DataSource.OVERDRIVE
elif not data_source_name:
data_source_name = DataSource.GUTENBERG
if fiction is None:
fiction = True
new_edition = False
if not presentation_edition:
new_edition = True
presentation_edition = self._edition(
title=title,
language=language,
authors=authors,
with_license_pool=with_license_pool,
with_open_access_download=with_open_access_download,
data_source_name=data_source_name,
series=series,
collection=collection,
self_hosted=self_hosted,
unlimited_access=unlimited_access,
)
if with_license_pool:
presentation_edition, pool = presentation_edition
if with_open_access_download:
pool.open_access = True
if self_hosted:
pool.open_access = False
pool.self_hosted = True
if unlimited_access:
pool.open_access = False
pool.unlimited_access = True
pools = [pool]
else:
pools = presentation_edition.license_pools
work, ignore = get_one_or_create(
self._db,
Work,
create_method_kwargs=dict(
audience=audience, fiction=fiction, quality=quality
),
id=self._id,
)
if genre:
if not isinstance(genre, Genre):
genre, ignore = Genre.lookup(self._db, genre, autocreate=True)
work.genres = [genre]
work.random = 0.5
work.set_presentation_edition(presentation_edition)
if pools:
# make sure the pool's presentation_edition is set,
# bc loan tests assume that.
if not work.license_pools:
for pool in pools:
work.license_pools.append(pool)
for pool in pools:
pool.set_presentation_edition()
# This is probably going to be used in an OPDS feed, so
# fake that the work is presentation ready.
work.presentation_ready = True
work.calculate_opds_entries(verbose=False)
return work
def _lane(
self,
display_name=None,
library=None,
parent=None,
genres=None,
languages=None,
fiction=None,
inherit_parent_restrictions=True,
):
display_name = display_name or self._str
library = library or self._default_library
lane, is_new = create(
self._db,
Lane,
library=library,
parent=parent,
display_name=display_name,
fiction=fiction,
inherit_parent_restrictions=inherit_parent_restrictions,
)
if is_new and parent:
lane.priority = len(parent.sublanes) - 1
if genres:
if not isinstance(genres, list):
genres = [genres]
for genre in genres:
if isinstance(genre, str):
genre, ignore = Genre.lookup(self._db, genre)
lane.genres.append(genre)
if languages:
if not isinstance(languages, list):
languages = [languages]
lane.languages = languages
return lane
def _slow_work(self, *args, **kwargs):
"""Create a work that closely resembles one that might be found in the
wild.
This is significantly slower than _work() but more reliable.
"""
work = self._work(*args, **kwargs)
work.calculate_presentation_edition()
work.calculate_opds_entries(verbose=False)
return work
def _add_generic_delivery_mechanism(self, license_pool):
"""Give a license pool a generic non-open-access delivery mechanism."""
data_source = license_pool.data_source
identifier = license_pool.identifier
content_type = Representation.EPUB_MEDIA_TYPE
drm_scheme = DeliveryMechanism.NO_DRM
return LicensePoolDeliveryMechanism.set(
data_source, identifier, content_type, drm_scheme, RightsStatus.IN_COPYRIGHT
)
def _coverage_record(
self,
edition,
coverage_source,
operation=None,
status=CoverageRecord.SUCCESS,
collection=None,
exception=None,
):
if isinstance(edition, Identifier):
identifier = edition
else:
identifier = edition.primary_identifier
record, ignore = get_one_or_create(
self._db,
CoverageRecord,
identifier=identifier,
data_source=coverage_source,
operation=operation,
collection=collection,
create_method_kwargs=dict(
timestamp=utc_now(),
status=status,
exception=exception,
),
)
return record
def _work_coverage_record(
self, work, operation=None, status=CoverageRecord.SUCCESS
):
record, ignore = get_one_or_create(
self._db,
WorkCoverageRecord,
work=work,
operation=operation,
create_method_kwargs=dict(
timestamp=utc_now(),
status=status,
),
)
return record
def _licensepool(
self,
edition,
open_access=True,
data_source_name=DataSource.GUTENBERG,
with_open_access_download=False,
set_edition_as_presentation=False,
collection=None,
self_hosted=False,
unlimited_access=False,
):
source = DataSource.lookup(self._db, data_source_name)
if not edition:
edition = self._edition(data_source_name)
collection = collection or self._default_collection
pool, ignore = get_one_or_create(
self._db,
LicensePool,
create_method_kwargs=dict(open_access=open_access),
identifier=edition.primary_identifier,
data_source=source,
collection=collection,
availability_time=utc_now(),
self_hosted=self_hosted,
unlimited_access=unlimited_access,
)
if set_edition_as_presentation:
pool.presentation_edition = edition
if with_open_access_download:
pool.open_access = True
url = "http://foo.com/" + self._str
media_type = MediaTypes.EPUB_MEDIA_TYPE
link, new = pool.identifier.add_link(
Hyperlink.OPEN_ACCESS_DOWNLOAD, url, source, media_type
)
# Add a DeliveryMechanism for this download
pool.set_delivery_mechanism(
media_type,
DeliveryMechanism.NO_DRM,
RightsStatus.GENERIC_OPEN_ACCESS,
link.resource,
)
representation, is_new = self._representation(
url, media_type, "Dummy content", mirrored=True
)
link.resource.representation = representation
else:
# Add a DeliveryMechanism for this licensepool
pool.set_delivery_mechanism(
MediaTypes.EPUB_MEDIA_TYPE,
DeliveryMechanism.ADOBE_DRM,
RightsStatus.UNKNOWN,
None,
)
if not unlimited_access:
pool.licenses_owned = pool.licenses_available = 1
return pool
def _license(
self,
pool,
identifier=None,
checkout_url=None,
status_url=None,
expires=None,
checkouts_left=None,
checkouts_available=None,
status=LicenseStatus.available,
terms_concurrency=None,
):
identifier = identifier or self._str
checkout_url = checkout_url or self._str
status_url = status_url or self._str
license, ignore = get_one_or_create(
self._db,
License,
identifier=identifier,
license_pool=pool,
checkout_url=checkout_url,
status_url=status_url,
expires=expires,
checkouts_left=checkouts_left,
checkouts_available=checkouts_available,
status=status,
terms_concurrency=terms_concurrency,
)
return license
def _representation(self, url=None, media_type=None, content=None, mirrored=False):
url = url or "http://foo.com/" + self._str
repr, is_new = get_one_or_create(self._db, Representation, url=url)
repr.media_type = media_type
if media_type and content:
if isinstance(content, str):
content = content.encode("utf8")
repr.content = content
repr.fetched_at = utc_now()
if mirrored:
repr.mirror_url = "http://foo.com/" + self._str
repr.mirrored_at = utc_now()
return repr, is_new
def _customlist(
self,
foreign_identifier=None,
name=None,
data_source_name=DataSource.NYT,
num_entries=1,
entries_exist_as_works=True,
):
data_source = DataSource.lookup(self._db, data_source_name)
foreign_identifier = foreign_identifier or self._str
now = utc_now()
customlist, ignore = get_one_or_create(
self._db,
CustomList,
create_method_kwargs=dict(
created=now,
updated=now,
name=name or self._str,
description=self._str,
),
data_source=data_source,
foreign_identifier=foreign_identifier,
)
editions = []
for i in range(num_entries):
if entries_exist_as_works:
work = self._work(with_open_access_download=True)
edition = work.presentation_edition
else:
edition = self._edition(data_source_name, title="Item %s" % i)
edition.permanent_work_id = "Permanent work ID %s" % self._str
customlist.add_entry(edition, "Annotation %s" % i, first_appearance=now)
editions.append(edition)
return customlist, editions
def _complaint(self, license_pool, type, source, detail, resolved=None):
complaint, is_new = Complaint.register(
license_pool, type, source, detail, resolved
)
return complaint
def _credential(
self, data_source_name=DataSource.GUTENBERG, type=None, patron=None
):
data_source = DataSource.lookup(self._db, data_source_name)
type = type or self._str
patron = patron or self._patron()
credential, is_new = Credential.persistent_token_create(
self._db, data_source, type, patron
)
return credential
def _external_integration(
self, protocol, goal=None, settings=None, libraries=None, **kwargs
):
integration = None
if not libraries:
integration, ignore = get_one_or_create(
self._db, ExternalIntegration, protocol=protocol, goal=goal
)
else:
if not isinstance(libraries, list):
libraries = [libraries]
# Try to find an existing integration for one of the given
# libraries.
for library in libraries:
integration = ExternalIntegration.lookup(
self._db, protocol, goal, library=libraries[0]
)
if integration:
break
if not integration:
# Otherwise, create a brand new integration specifically
# for the library.
integration = ExternalIntegration(
protocol=protocol,
goal=goal,
)
integration.libraries.extend(libraries)
self._db.add(integration)
for attr, value in list(kwargs.items()):
setattr(integration, attr, value)
settings = settings or dict()
for key, value in list(settings.items()):
integration.set_setting(key, value)
return integration
def _external_integration_link(
self,
integration=None,
library=None,
other_integration=None,
purpose="covers_mirror",
):
integration = integration or self._external_integration("some protocol")
other_integration = other_integration or self._external_integration(
"some other protocol"
)
library_id = library.id if library else None
external_integration_link, ignore = get_one_or_create(
self._db,
ExternalIntegrationLink,
library_id=library_id,
external_integration_id=integration.id,
other_integration_id=other_integration.id,
purpose=purpose,
)
return external_integration_link
def _delegated_patron_identifier(
self,
library_uri=None,
patron_identifier=None,
identifier_type=DelegatedPatronIdentifier.ADOBE_ACCOUNT_ID,
identifier=None,
):
"""Create a sample DelegatedPatronIdentifier"""
library_uri = library_uri or self._url
patron_identifier = patron_identifier or self._str
if callable(identifier):
make_id = identifier
else:
if not identifier:
identifier = self._str
def make_id():
return identifier
patron, is_new = DelegatedPatronIdentifier.get_one_or_create(
self._db, library_uri, patron_identifier, identifier_type, make_id
)
return patron
def _sample_ecosystem(self):
"""Creates an ecosystem of some sample work, pool, edition, and author
objects that all know each other.
"""
# make some authors
[bob], ignore = Contributor.lookup(self._db, "Bitshifter, Bob")
bob.family_name, bob.display_name = bob.default_names()
[alice], ignore = Contributor.lookup(self._db, "Adder, Alice")
alice.family_name, alice.display_name = alice.default_names()
edition_std_ebooks, pool_std_ebooks = self._edition(
DataSource.STANDARD_EBOOKS,
Identifier.URI,
with_license_pool=True,
with_open_access_download=True,
authors=[],
)
edition_std_ebooks.title = "The Standard Ebooks Title"
edition_std_ebooks.subtitle = "The Standard Ebooks Subtitle"
edition_std_ebooks.add_contributor(alice, Contributor.AUTHOR_ROLE)
edition_git, pool_git = self._edition(
DataSource.PROJECT_GITENBERG,
Identifier.GUTENBERG_ID,
with_license_pool=True,
with_open_access_download=True,
authors=[],
)
edition_git.title = "The GItenberg Title"
edition_git.subtitle = "The GItenberg Subtitle"
edition_git.add_contributor(bob, Contributor.AUTHOR_ROLE)
edition_git.add_contributor(alice, Contributor.AUTHOR_ROLE)
edition_gut, pool_gut = self._edition(
DataSource.GUTENBERG,
Identifier.GUTENBERG_ID,
with_license_pool=True,
with_open_access_download=True,
authors=[],
)
edition_gut.title = "The GUtenberg Title"
edition_gut.subtitle = "The GUtenberg Subtitle"
edition_gut.add_contributor(bob, Contributor.AUTHOR_ROLE)
work = self._work(presentation_edition=edition_git)
for p in pool_gut, pool_std_ebooks:
work.license_pools.append(p)
work.calculate_presentation()
return (
work,
pool_std_ebooks,
pool_git,
pool_gut,
edition_std_ebooks,
edition_git,
edition_gut,
alice,
bob,
)
def print_database_instance(self):
"""
Calls the class method that examines the current state of the database model
(whether it's been committed or not).
NOTE: If you set_trace, and hit "continue", you'll start seeing console output right
away, without waiting for the whole test to run and the standard output section to display.
You can also use nosetest --nocapture.
I use::
def test_name(self):
[code...]
set_trace()
self.print_database_instance() # TODO: remove before prod
[code...]
"""
if not "TESTING" in os.environ:
# we are on production, abort, abort!
logging.warn(
"Forgot to remove call to testing.py:DatabaseTest.print_database_instance() before pushing to production."
)
return
DatabaseTest.print_database_class(self._db)
return
@classmethod
def print_database_class(cls, db_connection):
"""
Prints to the console the entire contents of the database, as the unit test sees it.
Exists because unit tests don't persist db information, they create a memory
representation of the db state, and then roll the unit test-derived transactions back.
So we cannot see what's going on by going into postgres and running selects.
This is the in-test alternative to going into postgres.
Can be called from model and metadata classes as well as tests.
NOTE: The purpose of this method is for debugging.
Be careful of leaving it in code and potentially outputting
vast tracts of data into your output stream on production.
Call like this::
set_trace()
from testing import (l=
DatabaseTest,
)
_db = Session.object_session(self)
DatabaseTest.print_database_class(_db)
TODO: remove before prod
"""
if not "TESTING" in os.environ:
# we are on production, abort, abort!
logging.warn(
"Forgot to remove call to testing.py:DatabaseTest.print_database_class() before pushing to production."
)
return
works = db_connection.query(Work).all()
identifiers = db_connection.query(Identifier).all()
license_pools = db_connection.query(LicensePool).all()
editions = db_connection.query(Edition).all()
data_sources = db_connection.query(DataSource).all()
representations = db_connection.query(Representation).all()
if not works:
print("NO Work found")
for wCount, work in enumerate(works):
# pipe character at end of line helps see whitespace issues
print("Work[%s]=%s|" % (wCount, work))
if not work.license_pools:
print(" NO Work.LicensePool found")
for lpCount, license_pool in enumerate(work.license_pools):
print(" Work.LicensePool[%s]=%s|" % (lpCount, license_pool))
print(" Work.presentation_edition=%s|" % work.presentation_edition)
print("__________________________________________________________________\n")
if not identifiers:
print("NO Identifier found")
for iCount, identifier in enumerate(identifiers):
print("Identifier[%s]=%s|" % (iCount, identifier))
print(" Identifier.licensed_through=%s|" % identifier.licensed_through)
print("__________________________________________________________________\n")
if not license_pools:
print("NO LicensePool found")
for index, license_pool in enumerate(license_pools):
print("LicensePool[%s]=%s|" % (index, license_pool))
print(" LicensePool.work_id=%s|" % license_pool.work_id)
print(" LicensePool.data_source_id=%s|" % license_pool.data_source_id)
print(" LicensePool.identifier_id=%s|" % license_pool.identifier_id)
print(
" LicensePool.presentation_edition_id=%s|"
% license_pool.presentation_edition_id
)
print(" LicensePool.superceded=%s|" % license_pool.superceded)
print(" LicensePool.suppressed=%s|" % license_pool.suppressed)
print("__________________________________________________________________\n")
if not editions:
print("NO Edition found")
for index, edition in enumerate(editions):
# pipe character at end of line helps see whitespace issues
print("Edition[%s]=%s|" % (index, edition))
print(
" Edition.primary_identifier_id=%s|" % edition.primary_identifier_id
)
print(" Edition.permanent_work_id=%s|" % edition.permanent_work_id)
if edition.data_source:
print(" Edition.data_source.id=%s|" % edition.data_source.id)
print(" Edition.data_source.name=%s|" % edition.data_source.name)
else:
print(" No Edition.data_source.")
if edition.license_pool:
print(" Edition.license_pool.id=%s|" % edition.license_pool.id)
else:
print(" No Edition.license_pool.")
print(" Edition.title=%s|" % edition.title)
print(" Edition.author=%s|" % edition.author)
if not edition.author_contributors:
print(" NO Edition.author_contributor found")
for acCount, author_contributor in enumerate(edition.author_contributors):
print(
" Edition.author_contributor[%s]=%s|"
% (acCount, author_contributor)
)
print("__________________________________________________________________\n")
if not data_sources:
print("NO DataSource found")
for index, data_source in enumerate(data_sources):
print("DataSource[%s]=%s|" % (index, data_source))
print(" DataSource.id=%s|" % data_source.id)
print(" DataSource.name=%s|" % data_source.name)
print(" DataSource.offers_licenses=%s|" % data_source.offers_licenses)
print(" DataSource.editions=%s|" % data_source.editions)