/usr/share/pyshared/ZODB/tests/testConnection.py is in python-zodb 1:3.10.5-0ubuntu3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Unit tests for the Connection class."""
from __future__ import with_statement
import doctest
import unittest
from persistent import Persistent
import transaction
from ZODB.config import databaseFromString
from ZODB.utils import p64
from zope.interface.verify import verifyObject
import ZODB.tests.util
class ConnectionDotAdd(ZODB.tests.util.TestCase):
def setUp(self):
ZODB.tests.util.TestCase.setUp(self)
from ZODB.Connection import Connection
self.db = StubDatabase()
self.datamgr = Connection(self.db)
self.datamgr.open()
self.transaction = StubTransaction()
def check_add(self):
from ZODB.POSException import InvalidObjectReference
obj = StubObject()
self.assert_(obj._p_oid is None)
self.assert_(obj._p_jar is None)
self.datamgr.add(obj)
self.assert_(obj._p_oid is not None)
self.assert_(obj._p_jar is self.datamgr)
self.assert_(self.datamgr.get(obj._p_oid) is obj)
# Only first-class persistent objects may be added.
self.assertRaises(TypeError, self.datamgr.add, object())
# Adding to the same connection does not fail. Object keeps the
# same oid.
oid = obj._p_oid
self.datamgr.add(obj)
self.assertEqual(obj._p_oid, oid)
# Cannot add an object from a different connection.
obj2 = StubObject()
obj2._p_jar = object()
self.assertRaises(InvalidObjectReference, self.datamgr.add, obj2)
def checkResetOnAbort(self):
# Check that _p_oid and _p_jar are reset when a transaction is
# aborted.
obj = StubObject()
self.datamgr.add(obj)
oid = obj._p_oid
self.datamgr.abort(self.transaction)
self.assert_(obj._p_oid is None)
self.assert_(obj._p_jar is None)
self.assertRaises(KeyError, self.datamgr.get, oid)
def checkResetOnTpcAbort(self):
obj = StubObject()
self.datamgr.add(obj)
oid = obj._p_oid
# Simulate an error while committing some other object.
self.datamgr.tpc_begin(self.transaction)
# Let's pretend something bad happens here.
# Call tpc_abort, clearing everything.
self.datamgr.tpc_abort(self.transaction)
self.assert_(obj._p_oid is None)
self.assert_(obj._p_jar is None)
self.assertRaises(KeyError, self.datamgr.get, oid)
def checkTpcAbortAfterCommit(self):
obj = StubObject()
self.datamgr.add(obj)
oid = obj._p_oid
self.datamgr.tpc_begin(self.transaction)
self.datamgr.commit(self.transaction)
# Let's pretend something bad happened here.
self.datamgr.tpc_abort(self.transaction)
self.assert_(obj._p_oid is None)
self.assert_(obj._p_jar is None)
self.assertRaises(KeyError, self.datamgr.get, oid)
self.assertEquals(self.db.storage._stored, [oid])
def checkCommit(self):
obj = StubObject()
self.datamgr.add(obj)
oid = obj._p_oid
self.datamgr.tpc_begin(self.transaction)
self.datamgr.commit(self.transaction)
self.datamgr.tpc_finish(self.transaction)
self.assert_(obj._p_oid is oid)
self.assert_(obj._p_jar is self.datamgr)
# This next assert_ is covered by an assert in tpc_finish.
##self.assert_(not self.datamgr._added)
self.assertEquals(self.db.storage._stored, [oid])
self.assertEquals(self.db.storage._finished, [oid])
def checkModifyOnGetstate(self):
member = StubObject()
subobj = StubObject()
subobj.member = member
obj = ModifyOnGetStateObject(subobj)
self.datamgr.add(obj)
self.datamgr.tpc_begin(self.transaction)
self.datamgr.commit(self.transaction)
self.datamgr.tpc_finish(self.transaction)
storage = self.db.storage
self.assert_(obj._p_oid in storage._stored, "object was not stored")
self.assert_(subobj._p_oid in storage._stored,
"subobject was not stored")
self.assert_(member._p_oid in storage._stored, "member was not stored")
self.assert_(self.datamgr._added_during_commit is None)
def checkUnusedAddWorks(self):
# When an object is added, but not committed, it shouldn't be stored,
# but also it should be an error.
obj = StubObject()
self.datamgr.add(obj)
self.datamgr.tpc_begin(self.transaction)
self.datamgr.tpc_finish(self.transaction)
self.assert_(obj._p_oid not in self.datamgr._storage._stored)
def check__resetCacheResetsReader(self):
# https://bugs.launchpad.net/zodb/+bug/142667
old_cache = self.datamgr._cache
self.datamgr._resetCache()
new_cache = self.datamgr._cache
self.failIf(new_cache is old_cache)
self.failUnless(self.datamgr._reader._cache is new_cache)
class UserMethodTests(unittest.TestCase):
# add isn't tested here, because there are a bunch of traditional
# unit tests for it.
def test_root(self):
r"""doctest of root() method
The root() method is simple, and the tests are pretty minimal.
Ensure that a new database has a root and that it is a
PersistentMapping.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> root = cn.root()
>>> type(root).__name__
'PersistentMapping'
>>> root._p_oid
'\x00\x00\x00\x00\x00\x00\x00\x00'
>>> root._p_jar is cn
True
>>> db.close()
"""
def test_get(self):
r"""doctest of get() method
The get() method return the persistent object corresponding to
an oid.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> obj = cn.get(p64(0))
>>> obj._p_oid
'\x00\x00\x00\x00\x00\x00\x00\x00'
The object is a ghost.
>>> obj._p_state
-1
And multiple calls with the same oid, return the same object.
>>> obj2 = cn.get(p64(0))
>>> obj is obj2
True
If all references to the object are released, then a new
object will be returned. The cache doesn't keep unreferenced
ghosts alive. (The next object returned my still have the
same id, because Python may re-use the same memory.)
>>> del obj, obj2
>>> cn._cache.get(p64(0), None)
If the object is unghosted, then it will stay in the cache
after the last reference is released. (This is true only if
there is room in the cache and the object is recently used.)
>>> obj = cn.get(p64(0))
>>> obj._p_activate()
>>> y = id(obj)
>>> del obj
>>> obj = cn.get(p64(0))
>>> id(obj) == y
True
>>> obj._p_state
0
A request for an object that doesn't exist will raise a POSKeyError.
>>> cn.get(p64(1))
Traceback (most recent call last):
...
POSKeyError: 0x01
"""
def test_close(self):
r"""doctest of close() method
This is a minimal test, because most of the interesting
effects on closing a connection involve its interaction with the
database and the transaction.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
It's safe to close a connection multiple times.
>>> cn.close()
>>> cn.close()
>>> cn.close()
It's not possible to load or store objects once the storage is closed.
>>> cn.get(p64(0))
Traceback (most recent call last):
...
ConnectionStateError: The database connection is closed
>>> p = Persistent()
>>> cn.add(p)
Traceback (most recent call last):
...
ConnectionStateError: The database connection is closed
"""
def test_close_with_pending_changes(self):
r"""doctest to ensure close() w/ pending changes complains
>>> import transaction
Just opening and closing is fine.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> cn.close()
Opening, making a change, committing, and closing is fine.
>>> cn = db.open()
>>> cn.root()['a'] = 1
>>> transaction.commit()
>>> cn.close()
Opening, making a change, and aborting is fine.
>>> cn = db.open()
>>> cn.root()['a'] = 1
>>> transaction.abort()
>>> cn.close()
But trying to close with a change pending complains.
>>> cn = db.open()
>>> cn.root()['a'] = 10
>>> cn.close()
Traceback (most recent call last):
...
ConnectionStateError: Cannot close a connection joined to a transaction
This leaves the connection as it was, so we can still commit
the change.
>>> transaction.commit()
>>> cn2 = db.open()
>>> cn2.root()['a']
10
>>> cn.close(); cn2.close()
>>> db.close()
"""
def test_onCloseCallbacks(self):
r"""doctest of onCloseCallback() method
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
Every function registered is called, even if it raises an
exception. They are only called once.
>>> L = []
>>> def f():
... L.append("f")
>>> def g():
... L.append("g")
... return 1 / 0
>>> cn.onCloseCallback(g)
>>> cn.onCloseCallback(f)
>>> cn.close()
>>> L
['g', 'f']
>>> del L[:]
>>> cn.close()
>>> L
[]
The implementation keeps a list of callbacks that is reset
to a class variable (which is bound to None) after the connection
is closed.
>>> cn._Connection__onCloseCallbacks
"""
def test_close_dispatches_to_activity_monitors(self):
r"""doctest that connection close updates activity monitors
Set up a multi-database:
>>> db1 = ZODB.DB(None)
>>> db2 = ZODB.DB(None, databases=db1.databases, database_name='2',
... cache_size=10)
>>> conn1 = db1.open()
>>> conn2 = conn1.get_connection('2')
Add activity monitors to both dbs:
>>> from ZODB.ActivityMonitor import ActivityMonitor
>>> db1.setActivityMonitor(ActivityMonitor())
>>> db2.setActivityMonitor(ActivityMonitor())
Commit a transaction that affects both connections:
>>> conn1.root()[0] = conn1.root().__class__()
>>> conn2.root()[0] = conn2.root().__class__()
>>> transaction.commit()
After closing the primary connection, both monitors should be up to
date:
>>> conn1.close()
>>> len(db1.getActivityMonitor().log)
1
>>> len(db2.getActivityMonitor().log)
1
"""
def test_db(self):
r"""doctest of db() method
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> cn.db() is db
True
>>> cn.close()
>>> cn.db() is db
True
"""
def test_isReadOnly(self):
r"""doctest of isReadOnly() method
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> cn.isReadOnly()
False
>>> cn.close()
>>> cn.isReadOnly()
Traceback (most recent call last):
...
ConnectionStateError: The database connection is closed
An expedient way to create a read-only storage:
>>> db.storage.isReadOnly = lambda: True
>>> cn = db.open()
>>> cn.isReadOnly()
True
"""
def test_cache(self):
r"""doctest of cacheMinimize().
Thus test us minimal, just verifying that the method can be called
and has some effect. We need other tests that verify the cache works
as intended.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> r = cn.root()
>>> cn.cacheMinimize()
>>> r._p_state
-1
>>> r._p_activate()
>>> r._p_state # up to date
0
>>> cn.cacheMinimize()
>>> r._p_state # ghost again
-1
"""
def test_transaction_retry_convenience():
"""
Simple test to verify integration with the transaction retry
helper my verifying that we can raise ConflictError and have it
handled properly.
This is an adaptation of the convenience tests in transaction.
>>> db = ZODB.tests.util.DB()
>>> conn = db.open()
>>> dm = conn.root()
>>> ntry = 0
>>> with transaction.manager:
... dm['ntry'] = 0
>>> import ZODB.POSException
>>> for attempt in transaction.manager.attempts():
... with attempt as t:
... t.note('test')
... print dm['ntry'], ntry
... ntry += 1
... dm['ntry'] = ntry
... if ntry % 3:
... raise ZODB.POSException.ConflictError()
0 0
0 1
0 2
"""
class InvalidationTests(unittest.TestCase):
# It's harder to write serious tests, because some of the critical
# correctness issues relate to concurrency. We'll have to depend
# on the various concurrent updates and NZODBThreads tests to
# handle these.
def test_invalidate(self):
r"""
This test initializes the database with several persistent
objects, then manually delivers invalidations and verifies that
they have the expected effect.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> p1 = Persistent()
>>> p2 = Persistent()
>>> p3 = Persistent()
>>> r = cn.root()
>>> r.update(dict(p1=p1, p2=p2, p3=p3))
>>> transaction.commit()
Transaction ids are 8-byte strings, just like oids; p64() will
create one from an int.
>>> cn.invalidate(p64(1), {p1._p_oid: 1})
>>> cn._txn_time
'\x00\x00\x00\x00\x00\x00\x00\x01'
>>> p1._p_oid in cn._invalidated
True
>>> p2._p_oid in cn._invalidated
False
>>> cn.invalidate(p64(10), {p2._p_oid: 1, p64(76): 1})
>>> cn._txn_time
'\x00\x00\x00\x00\x00\x00\x00\x01'
>>> p1._p_oid in cn._invalidated
True
>>> p2._p_oid in cn._invalidated
True
Calling invalidate() doesn't affect the object state until
a transaction boundary.
>>> p1._p_state
0
>>> p2._p_state
0
>>> p3._p_state
0
The sync() method will abort the current transaction and
process any pending invalidations.
>>> cn.sync()
>>> p1._p_state
-1
>>> p2._p_state
-1
>>> p3._p_state
0
>>> cn._invalidated
set([])
"""
def test_invalidateCache():
"""The invalidateCache method invalidates a connection's cache. It also
prevents reads until the end of a transaction::
>>> from ZODB.tests.util import DB
>>> import transaction
>>> db = DB()
>>> tm = transaction.TransactionManager()
>>> connection = db.open(transaction_manager=tm)
>>> connection.root()['a'] = StubObject()
>>> connection.root()['a'].x = 1
>>> connection.root()['b'] = StubObject()
>>> connection.root()['b'].x = 1
>>> connection.root()['c'] = StubObject()
>>> connection.root()['c'].x = 1
>>> tm.commit()
>>> connection.root()['b']._p_deactivate()
>>> connection.root()['c'].x = 2
So we have a connection and an active transaction with some modifications.
Lets call invalidateCache:
>>> connection.invalidateCache()
Now, if we try to load an object, we'll get a read conflict:
>>> connection.root()['b'].x
Traceback (most recent call last):
...
ReadConflictError: database read conflict error
If we try to commit the transaction, we'll get a conflict error:
>>> tm.commit()
Traceback (most recent call last):
...
ConflictError: database conflict error
and the cache will have been cleared:
>>> print connection.root()['a']._p_changed
None
>>> print connection.root()['b']._p_changed
None
>>> print connection.root()['c']._p_changed
None
But we'll be able to access data again:
>>> connection.root()['b'].x
1
Aborting a transaction after a read conflict also lets us read data and go
on about our business:
>>> connection.invalidateCache()
>>> connection.root()['c'].x
Traceback (most recent call last):
...
ReadConflictError: database read conflict error
>>> tm.abort()
>>> connection.root()['c'].x
1
>>> connection.root()['c'].x = 2
>>> tm.commit()
>>> db.close()
"""
def connection_root_convenience():
"""Connection root attributes can now be used as objects with attributes
>>> db = ZODB.tests.util.DB()
>>> conn = db.open()
>>> conn.root.x
Traceback (most recent call last):
...
AttributeError: x
>>> del conn.root.x
Traceback (most recent call last):
...
AttributeError: x
>>> conn.root()['x'] = 1
>>> conn.root.x
1
>>> conn.root.y = 2
>>> sorted(conn.root().items())
[('x', 1), ('y', 2)]
>>> conn.root
<root: x y>
>>> del conn.root.x
>>> sorted(conn.root().items())
[('y', 2)]
>>> conn.root.rather_long_name = 1
>>> conn.root.rather_long_name2 = 1
>>> conn.root.rather_long_name4 = 1
>>> conn.root.rather_long_name5 = 1
>>> conn.root
<root: rather_long_name rather_long_name2 rather_long_name4 ...>
"""
class proper_ghost_initialization_with_empty__p_deactivate_class(Persistent):
def _p_deactivate(self):
pass
def proper_ghost_initialization_with_empty__p_deactivate():
"""
See https://bugs.launchpad.net/zodb/+bug/185066
>>> db = ZODB.tests.util.DB()
>>> conn = db.open()
>>> C = proper_ghost_initialization_with_empty__p_deactivate_class
>>> conn.root.x = x = C()
>>> conn.root.x.y = 1
>>> transaction.commit()
>>> conn2 = db.open()
>>> conn2.root.x._p_changed
>>> conn2.root.x.y
1
"""
def readCurrent():
r"""
The connection's readCurrent method is called to provide a higher
level of consistency in cases where an object if read to compute an
update to a separate object. When this is used, the
checkCurrentSerialInTransaction method on the storage is called in
2-phase commit.
To demonstrate this, we'll create a storage and give it a test
implementation of checkCurrentSerialInTransaction.
>>> import ZODB.MappingStorage
>>> store = ZODB.MappingStorage.MappingStorage()
>>> from ZODB.POSException import ReadConflictError
>>> bad = set()
>>> def checkCurrentSerialInTransaction(oid, serial, trans):
... print 'checkCurrentSerialInTransaction', `oid`
... if not trans == transaction.get(): print 'oops'
... if oid in bad:
... raise ReadConflictError(oid=oid)
>>> store.checkCurrentSerialInTransaction = checkCurrentSerialInTransaction
Now, we'll use the storage as usual. checkCurrentSerialInTransaction
won't normally be called:
>>> db = ZODB.DB(store)
>>> conn = db.open()
>>> conn.root.a = ZODB.tests.util.P('a')
>>> conn.root.b = ZODB.tests.util.P('b')
>>> transaction.commit()
If we call readCurrent for an object and we modify another object,
then checkCurrentSerialInTransaction will be called for the object
readCurrent was called on.
>>> conn.readCurrent(conn.root.a)
>>> conn.root.b.x = 0
>>> transaction.commit()
checkCurrentSerialInTransaction '\x00\x00\x00\x00\x00\x00\x00\x01'
It doesn't matter how often we call readCurrent,
checkCurrentSerialInTransaction will be called only once:
>>> conn.readCurrent(conn.root.a)
>>> conn.readCurrent(conn.root.a)
>>> conn.readCurrent(conn.root.a)
>>> conn.readCurrent(conn.root.a)
>>> conn.root.b.x += 1
>>> transaction.commit()
checkCurrentSerialInTransaction '\x00\x00\x00\x00\x00\x00\x00\x01'
checkCurrentSerialInTransaction won't be called if another object
isn't modified:
>>> conn.readCurrent(conn.root.a)
>>> transaction.commit()
Or if the object it was called on is modified:
>>> conn.readCurrent(conn.root.a)
>>> conn.root.a.x = 0
>>> conn.root.b.x += 1
>>> transaction.commit()
If the storage raises a conflict error, it'll be propigated:
>>> _ = str(conn.root.a) # do read
>>> bad.add(conn.root.a._p_oid)
>>> conn.readCurrent(conn.root.a)
>>> conn.root.b.x += 1
>>> transaction.commit()
Traceback (most recent call last):
...
ReadConflictError: database read conflict error (oid 0x01)
>>> transaction.abort()
The conflict error will cause the affected object to be invalidated:
>>> conn.root.a._p_changed
The storage may raise it later:
>>> def checkCurrentSerialInTransaction(oid, serial, trans):
... if not trans == transaction.get(): print 'oops'
... print 'checkCurrentSerialInTransaction', `oid`
... store.badness = ReadConflictError(oid=oid)
>>> def tpc_vote(t):
... if store.badness:
... badness = store.badness
... store.badness = None
... raise badness
>>> store.checkCurrentSerialInTransaction = checkCurrentSerialInTransaction
>>> store.badness = None
>>> store.tpc_vote = tpc_vote
It will still be propigated:
>>> _ = str(conn.root.a) # do read
>>> conn.readCurrent(conn.root.a)
>>> conn.root.b.x = +1
>>> transaction.commit()
Traceback (most recent call last):
...
ReadConflictError: database read conflict error (oid 0x01)
>>> transaction.abort()
The conflict error will cause the affected object to be invalidated:
>>> conn.root.a._p_changed
Read checks don't leak accross transactions:
>>> conn.readCurrent(conn.root.a)
>>> transaction.commit()
>>> conn.root.b.x = +1
>>> transaction.commit()
Read checks to work accross savepoints.
>>> conn.readCurrent(conn.root.a)
>>> conn.root.b.x = +1
>>> _ = transaction.savepoint()
>>> transaction.commit()
Traceback (most recent call last):
...
ReadConflictError: database read conflict error (oid 0x01)
>>> transaction.abort()
>>> conn.readCurrent(conn.root.a)
>>> _ = transaction.savepoint()
>>> conn.root.b.x = +1
>>> transaction.commit()
Traceback (most recent call last):
...
ReadConflictError: database read conflict error (oid 0x01)
>>> transaction.abort()
"""
def cache_management_of_subconnections():
"""Make that cache management works for subconnections.
When we use multi-databases, we open a connection in one database and
access connections to other databases through it. This test verifies
thatcache management is applied to all of the connections.
Set up a multi-database:
>>> db1 = ZODB.DB(None)
>>> db2 = ZODB.DB(None, databases=db1.databases, database_name='2',
... cache_size=10)
>>> conn1 = db1.open()
>>> conn2 = conn1.get_connection('2')
Populate it with some data, more than will fit in the cache:
>>> for i in range(100):
... conn2.root()[i] = conn2.root().__class__()
Upon commit, the cache is reduced to the cache size:
>>> transaction.commit()
>>> conn2._cache.cache_non_ghost_count
10
Fill it back up:
>>> for i in range(100):
... _ = str(conn2.root()[i])
>>> conn2._cache.cache_non_ghost_count
101
Doing cache GC on the primary also does it on the secondary:
>>> conn1.cacheGC()
>>> conn2._cache.cache_non_ghost_count
10
Ditto for cache minimize:
>>> conn1.cacheMinimize()
>>> conn2._cache.cache_non_ghost_count
0
Fill it back up:
>>> for i in range(100):
... _ = str(conn2.root()[i])
>>> conn2._cache.cache_non_ghost_count
101
GC is done on reopen:
>>> conn1.close()
>>> db1.open() is conn1
True
>>> conn2 is conn1.get_connection('2')
True
>>> conn2._cache.cache_non_ghost_count
10
"""
class C_invalidations_of_new_objects_work_after_savepoint(Persistent):
def __init__(self):
self.settings = 1
def _p_invalidate(self):
print 'INVALIDATE', self.settings
Persistent._p_invalidate(self)
print self.settings # POSKeyError here
def abort_of_savepoint_creating_new_objects_w_exotic_invalidate_doesnt_break():
r"""
Before, the following would fail with a POSKeyError, which was
somewhat surprizing, in a very edgy sort of way. :)
Really, when an object add is aborted, the object should be "removed" from
the db and its invalidatuon method shouldm't even be called:
>>> conn = ZODB.connection(None)
>>> conn.root.x = x = C_invalidations_of_new_objects_work_after_savepoint()
>>> _ = transaction.savepoint()
>>> x._p_oid
'\x00\x00\x00\x00\x00\x00\x00\x01'
>>> x._p_jar is conn
True
>>> transaction.abort()
After the abort, the oid and jar are None:
>>> x._p_oid
>>> x._p_jar
"""
class Clp9460655(Persistent):
def __init__(self, word, id):
super(Clp9460655, self).__init__()
self.id = id
self._word = word
def lp9460655():
r"""
>>> conn = ZODB.connection(None)
>>> root = conn.root()
>>> Word = Clp9460655
>>> from BTrees.OOBTree import OOBTree
>>> data = root['data'] = OOBTree()
>>> commonWords = []
>>> count = "0"
>>> for x in ('hello', 'world', 'how', 'are', 'you'):
... commonWords.append(Word(x, count))
... count = str(int(count) + 1)
>>> sv = transaction.savepoint()
>>> for word in commonWords:
... sv2 = transaction.savepoint()
... data[word.id] = word
>>> sv.rollback()
>>> print commonWords[1].id # raises POSKeyError
1
"""
def lp615758_transaction_abort_Incomplete_cleanup_for_new_objects():
r"""
As the following"DocTest" demonstrates, "abort" forgets to
reset "_p_changed" for new (i.e. "added") objects.
>>> class P(Persistent): pass
...
>>> c = ZODB.connection(None)
>>> obj = P()
>>> c.add(obj)
>>> obj.x = 1
>>> obj._p_changed
True
>>> transaction.abort()
>>> obj._p_changed
False
>>> c.close()
"""
class Clp485456_setattr_in_getstate_doesnt_cause_multiple_stores(Persistent):
def __getstate__(self):
self.got = 1
return self.__dict__.copy()
def lp485456_setattr_in_setstate_doesnt_cause_multiple_stores():
r"""
>>> C = Clp485456_setattr_in_getstate_doesnt_cause_multiple_stores
>>> conn = ZODB.connection(None)
>>> oldstore = conn._storage.store
>>> def store(oid, *args):
... print 'storing', repr(oid)
... return oldstore(oid, *args)
>>> conn._storage.store = store
When we commit a change, we only get a single store call
>>> conn.root.x = C()
>>> transaction.commit()
storing '\x00\x00\x00\x00\x00\x00\x00\x00'
storing '\x00\x00\x00\x00\x00\x00\x00\x01'
>>> conn.add(C())
>>> transaction.commit()
storing '\x00\x00\x00\x00\x00\x00\x00\x02'
We still see updates:
>>> conn.root.x.y = 1
>>> transaction.commit()
storing '\x00\x00\x00\x00\x00\x00\x00\x01'
Not not non-updates:
>>> transaction.commit()
Let's try some combinations with savepoints:
>>> conn.root.n = 0
>>> _ = transaction.savepoint()
>>> oldspstore = conn._storage.store
>>> def store(oid, *args):
... print 'savepoint storing', repr(oid)
... return oldspstore(oid, *args)
>>> conn._storage.store = store
>>> conn.root.y = C()
>>> _ = transaction.savepoint()
savepoint storing '\x00\x00\x00\x00\x00\x00\x00\x00'
savepoint storing '\x00\x00\x00\x00\x00\x00\x00\x03'
>>> conn.root.y.x = 1
>>> _ = transaction.savepoint()
savepoint storing '\x00\x00\x00\x00\x00\x00\x00\x03'
>>> transaction.commit()
storing '\x00\x00\x00\x00\x00\x00\x00\x00'
storing '\x00\x00\x00\x00\x00\x00\x00\x03'
>>> conn.close()
"""
class _PlayPersistent(Persistent):
def setValueWithSize(self, size=0): self.value = size*' '
__init__ = setValueWithSize
class EstimatedSizeTests(ZODB.tests.util.TestCase):
"""check that size estimations are handled correctly."""
def setUp(self):
ZODB.tests.util.TestCase.setUp(self)
self.db = db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
self.conn = c = db.open()
self.obj = obj = _PlayPersistent()
c.root()['obj'] = obj
transaction.commit()
def test_size_set_on_write_commit(self):
obj, cache = self.obj, self.conn._cache
# we have just written "obj". Its size should not be zero
size, cache_size = obj._p_estimated_size, cache.total_estimated_size
self.assert_(size > 0)
self.assert_(cache_size > size)
# increase the size, write again and check that the size changed
obj.setValueWithSize(1000)
transaction.commit()
new_size = obj._p_estimated_size
self.assert_(new_size > size)
self.assertEqual(cache.total_estimated_size,
cache_size + new_size - size)
def test_size_set_on_write_savepoint(self):
obj, cache = self.obj, self.conn._cache
# we have just written "obj". Its size should not be zero
size, cache_size = obj._p_estimated_size, cache.total_estimated_size
# increase the size, write again and check that the size changed
obj.setValueWithSize(1000)
transaction.savepoint()
new_size = obj._p_estimated_size
self.assert_(new_size > size)
self.assertEqual(cache.total_estimated_size,
cache_size + new_size - size)
def test_size_set_on_load(self):
c = self.db.open() # new connection
obj = c.root()['obj']
# the object is still a ghost and '_p_estimated_size' not yet set
# access to unghost
cache = c._cache
cache_size = cache.total_estimated_size
obj.value
size = obj._p_estimated_size
self.assert_(size > 0)
self.assertEqual(cache.total_estimated_size, cache_size + size)
# we test here as well that the deactivation works reduced the cache
# size
obj._p_deactivate()
self.assertEqual(cache.total_estimated_size, cache_size)
def test_configuration(self):
# verify defaults ....
expected = 0
# ... on db
db = self.db
self.assertEqual(db.getCacheSizeBytes(), expected)
self.assertEqual(db.getHistoricalCacheSizeBytes(), expected)
# ... on connection
conn = self.conn
self.assertEqual(conn._cache.cache_size_bytes, expected)
# verify explicit setting ...
expected = 10000
# ... on db
db = databaseFromString("<zodb>\n"
" cache-size-bytes %d\n"
" historical-cache-size-bytes %d\n"
" <mappingstorage />\n"
"</zodb>"
% (expected, expected+1)
)
self.assertEqual(db.getCacheSizeBytes(), expected)
self.assertEqual(db.getHistoricalCacheSizeBytes(), expected+1)
# ... on connectionB
conn = db.open()
self.assertEqual(conn._cache.cache_size_bytes, expected)
# test huge (larger than 4 byte) size limit
db = databaseFromString("<zodb>\n"
" cache-size-bytes 8GB\n"
" <mappingstorage />\n"
"</zodb>"
)
self.assertEqual(db.getCacheSizeBytes(), 0x1L << 33)
def test_cache_garbage_collection(self):
db = self.db
# activate size based cache garbage collection
db.setCacheSizeBytes(1)
conn = self.conn
cache = conn._cache
# verify the change worked as expected
self.assertEqual(cache.cache_size_bytes, 1)
# verify our entrance assumption is fullfilled
self.assert_(cache.total_estimated_size > 1)
conn.cacheGC()
self.assert_(cache.total_estimated_size <= 1)
# sanity check
self.assert_(cache.total_estimated_size >= 0)
def test_cache_garbage_collection_shrinking_object(self):
db = self.db
# activate size based cache garbage collection
db.setCacheSizeBytes(1000)
obj, conn, cache = self.obj, self.conn, self.conn._cache
# verify the change worked as expected
self.assertEqual(cache.cache_size_bytes, 1000)
# verify our entrance assumption is fullfilled
self.assert_(cache.total_estimated_size > 1)
# give the objects some size
obj.setValueWithSize(500)
transaction.savepoint()
self.assert_(cache.total_estimated_size > 500)
# make the object smaller
obj.setValueWithSize(100)
transaction.savepoint()
# make sure there was no overflow
self.assert_(cache.total_estimated_size != 0)
# the size is not larger than the allowed maximum
self.assert_(cache.total_estimated_size <= 1000)
# ---- stubs
class StubObject(Persistent):
pass
class StubTransaction:
pass
class ErrorOnGetstateException(Exception):
pass
class ErrorOnGetstateObject(Persistent):
def __getstate__(self):
raise ErrorOnGetstateException
class ModifyOnGetStateObject(Persistent):
def __init__(self, p):
self._v_p = p
def __getstate__(self):
self._p_jar.add(self._v_p)
self.p = self._v_p
return Persistent.__getstate__(self)
class StubStorage:
"""Very simple in-memory storage that does *just* enough to support tests.
Only one concurrent transaction is supported.
Voting is not supported.
Inspect self._stored and self._finished to see how the storage has been
used during a unit test. Whenever an object is stored in the store()
method, its oid is appended to self._stored. When a transaction is
finished, the oids that have been stored during the transaction are
appended to self._finished.
"""
# internal
_oid = 1
_transaction = None
def __init__(self):
# internal
self._stored = []
self._finished = []
self._data = {}
self._transdata = {}
self._transstored = []
def new_oid(self):
oid = str(self._oid)
self._oid += 1
return oid
def sortKey(self):
return 'StubStorage sortKey'
def tpc_begin(self, transaction):
if transaction is None:
raise TypeError('transaction may not be None')
elif self._transaction is None:
self._transaction = transaction
elif self._transaction != transaction:
raise RuntimeError(
'StubStorage uses only one transaction at a time')
def tpc_abort(self, transaction):
if transaction is None:
raise TypeError('transaction may not be None')
elif self._transaction != transaction:
raise RuntimeError(
'StubStorage uses only one transaction at a time')
del self._transaction
self._transdata.clear()
def tpc_finish(self, transaction, callback):
if transaction is None:
raise TypeError('transaction may not be None')
elif self._transaction != transaction:
raise RuntimeError(
'StubStorage uses only one transaction at a time')
self._finished.extend(self._transstored)
self._data.update(self._transdata)
callback(transaction)
del self._transaction
self._transdata.clear()
self._transstored = []
def load(self, oid, version=''):
if version != '':
raise TypeError('StubStorage does not support versions.')
return self._data[oid]
def store(self, oid, serial, p, version, transaction):
if version != '':
raise TypeError('StubStorage does not support versions.')
if transaction is None:
raise TypeError('transaction may not be None')
elif self._transaction != transaction:
raise RuntimeError(
'StubStorage uses only one transaction at a time')
self._stored.append(oid)
self._transstored.append(oid)
self._transdata[oid] = (p, serial)
# Explicitly returing None, as we're not pretending to be a ZEO
# storage
return None
class TestConnectionInterface(unittest.TestCase):
def test_connection_interface(self):
from ZODB.interfaces import IConnection
db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
cn = db.open()
verifyObject(IConnection, cn)
class StubDatabase:
def __init__(self):
self.storage = StubStorage()
self.new_oid = self.storage.new_oid
classFactory = None
database_name = 'stubdatabase'
databases = {'stubdatabase': database_name}
def invalidate(self, transaction, dict_with_oid_keys, connection):
pass
large_record_size = 1<<30
def test_suite():
s = unittest.makeSuite(ConnectionDotAdd, 'check')
s.addTest(doctest.DocTestSuite())
s.addTest(unittest.makeSuite(TestConnectionInterface))
s.addTest(unittest.makeSuite(EstimatedSizeTests))
return s
|