PageRenderTime 3486ms CodeModel.GetById 67ms RepoModel.GetById 18ms app.codeStats 1ms

/tests/regressiontests/multiple_database/tests.py

https://code.google.com/p/mango-py/
Python | 1884 lines | 1212 code | 385 blank | 287 comment | 92 complexity | b122edd90b14e13b1de9fd9eb7363263 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. import datetime
  2. import pickle
  3. import sys
  4. from StringIO import StringIO
  5. from django.conf import settings
  6. from django.contrib.auth.models import User
  7. from django.core import management
  8. from django.db import connections, router, DEFAULT_DB_ALIAS
  9. from django.db.models import signals
  10. from django.db.utils import ConnectionRouter
  11. from django.test import TestCase
  12. from models import Book, Person, Pet, Review, UserProfile
  13. try:
  14. # we only have these models if the user is using multi-db, it's safe the
  15. # run the tests without them though.
  16. from models import Article, article_using
  17. except ImportError:
  18. pass
  19. class QueryTestCase(TestCase):
  20. multi_db = True
  21. def test_db_selection(self):
  22. "Check that querysets will use the default database by default"
  23. self.assertEqual(Book.objects.db, DEFAULT_DB_ALIAS)
  24. self.assertEqual(Book.objects.all().db, DEFAULT_DB_ALIAS)
  25. self.assertEqual(Book.objects.using('other').db, 'other')
  26. self.assertEqual(Book.objects.db_manager('other').db, 'other')
  27. self.assertEqual(Book.objects.db_manager('other').all().db, 'other')
  28. def test_default_creation(self):
  29. "Objects created on the default database don't leak onto other databases"
  30. # Create a book on the default database using create()
  31. Book.objects.create(title="Pro Django",
  32. published=datetime.date(2008, 12, 16))
  33. # Create a book on the default database using a save
  34. dive = Book()
  35. dive.title="Dive into Python"
  36. dive.published = datetime.date(2009, 5, 4)
  37. dive.save()
  38. # Check that book exists on the default database, but not on other database
  39. try:
  40. Book.objects.get(title="Pro Django")
  41. Book.objects.using('default').get(title="Pro Django")
  42. except Book.DoesNotExist:
  43. self.fail('"Dive Into Python" should exist on default database')
  44. self.assertRaises(Book.DoesNotExist,
  45. Book.objects.using('other').get,
  46. title="Pro Django"
  47. )
  48. try:
  49. Book.objects.get(title="Dive into Python")
  50. Book.objects.using('default').get(title="Dive into Python")
  51. except Book.DoesNotExist:
  52. self.fail('"Dive into Python" should exist on default database')
  53. self.assertRaises(Book.DoesNotExist,
  54. Book.objects.using('other').get,
  55. title="Dive into Python"
  56. )
  57. def test_other_creation(self):
  58. "Objects created on another database don't leak onto the default database"
  59. # Create a book on the second database
  60. Book.objects.using('other').create(title="Pro Django",
  61. published=datetime.date(2008, 12, 16))
  62. # Create a book on the default database using a save
  63. dive = Book()
  64. dive.title="Dive into Python"
  65. dive.published = datetime.date(2009, 5, 4)
  66. dive.save(using='other')
  67. # Check that book exists on the default database, but not on other database
  68. try:
  69. Book.objects.using('other').get(title="Pro Django")
  70. except Book.DoesNotExist:
  71. self.fail('"Dive Into Python" should exist on other database')
  72. self.assertRaises(Book.DoesNotExist,
  73. Book.objects.get,
  74. title="Pro Django"
  75. )
  76. self.assertRaises(Book.DoesNotExist,
  77. Book.objects.using('default').get,
  78. title="Pro Django"
  79. )
  80. try:
  81. Book.objects.using('other').get(title="Dive into Python")
  82. except Book.DoesNotExist:
  83. self.fail('"Dive into Python" should exist on other database')
  84. self.assertRaises(Book.DoesNotExist,
  85. Book.objects.get,
  86. title="Dive into Python"
  87. )
  88. self.assertRaises(Book.DoesNotExist,
  89. Book.objects.using('default').get,
  90. title="Dive into Python"
  91. )
  92. def test_basic_queries(self):
  93. "Queries are constrained to a single database"
  94. dive = Book.objects.using('other').create(title="Dive into Python",
  95. published=datetime.date(2009, 5, 4))
  96. dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4))
  97. self.assertEqual(dive.title, "Dive into Python")
  98. self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, published=datetime.date(2009, 5, 4))
  99. dive = Book.objects.using('other').get(title__icontains="dive")
  100. self.assertEqual(dive.title, "Dive into Python")
  101. self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title__icontains="dive")
  102. dive = Book.objects.using('other').get(title__iexact="dive INTO python")
  103. self.assertEqual(dive.title, "Dive into Python")
  104. self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title__iexact="dive INTO python")
  105. dive = Book.objects.using('other').get(published__year=2009)
  106. self.assertEqual(dive.title, "Dive into Python")
  107. self.assertEqual(dive.published, datetime.date(2009, 5, 4))
  108. self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, published__year=2009)
  109. years = Book.objects.using('other').dates('published', 'year')
  110. self.assertEqual([o.year for o in years], [2009])
  111. years = Book.objects.using('default').dates('published', 'year')
  112. self.assertEqual([o.year for o in years], [])
  113. months = Book.objects.using('other').dates('published', 'month')
  114. self.assertEqual([o.month for o in months], [5])
  115. months = Book.objects.using('default').dates('published', 'month')
  116. self.assertEqual([o.month for o in months], [])
  117. def test_m2m_separation(self):
  118. "M2M fields are constrained to a single database"
  119. # Create a book and author on the default database
  120. pro = Book.objects.create(title="Pro Django",
  121. published=datetime.date(2008, 12, 16))
  122. marty = Person.objects.create(name="Marty Alchin")
  123. # Create a book and author on the other database
  124. dive = Book.objects.using('other').create(title="Dive into Python",
  125. published=datetime.date(2009, 5, 4))
  126. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  127. # Save the author relations
  128. pro.authors = [marty]
  129. dive.authors = [mark]
  130. # Inspect the m2m tables directly.
  131. # There should be 1 entry in each database
  132. self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
  133. self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
  134. # Check that queries work across m2m joins
  135. self.assertEqual(list(Book.objects.using('default').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
  136. [u'Pro Django'])
  137. self.assertEqual(list(Book.objects.using('other').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
  138. [])
  139. self.assertEqual(list(Book.objects.using('default').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  140. [])
  141. self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  142. [u'Dive into Python'])
  143. # Reget the objects to clear caches
  144. dive = Book.objects.using('other').get(title="Dive into Python")
  145. mark = Person.objects.using('other').get(name="Mark Pilgrim")
  146. # Retrive related object by descriptor. Related objects should be database-baound
  147. self.assertEqual(list(dive.authors.all().values_list('name', flat=True)),
  148. [u'Mark Pilgrim'])
  149. self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)),
  150. [u'Dive into Python'])
  151. def test_m2m_forward_operations(self):
  152. "M2M forward manipulations are all constrained to a single DB"
  153. # Create a book and author on the other database
  154. dive = Book.objects.using('other').create(title="Dive into Python",
  155. published=datetime.date(2009, 5, 4))
  156. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  157. # Save the author relations
  158. dive.authors = [mark]
  159. # Add a second author
  160. john = Person.objects.using('other').create(name="John Smith")
  161. self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
  162. [])
  163. dive.authors.add(john)
  164. self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  165. [u'Dive into Python'])
  166. self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
  167. [u'Dive into Python'])
  168. # Remove the second author
  169. dive.authors.remove(john)
  170. self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  171. [u'Dive into Python'])
  172. self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
  173. [])
  174. # Clear all authors
  175. dive.authors.clear()
  176. self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  177. [])
  178. self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
  179. [])
  180. # Create an author through the m2m interface
  181. dive.authors.create(name='Jane Brown')
  182. self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  183. [])
  184. self.assertEqual(list(Book.objects.using('other').filter(authors__name='Jane Brown').values_list('title', flat=True)),
  185. [u'Dive into Python'])
  186. def test_m2m_reverse_operations(self):
  187. "M2M reverse manipulations are all constrained to a single DB"
  188. # Create a book and author on the other database
  189. dive = Book.objects.using('other').create(title="Dive into Python",
  190. published=datetime.date(2009, 5, 4))
  191. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  192. # Save the author relations
  193. dive.authors = [mark]
  194. # Create a second book on the other database
  195. grease = Book.objects.using('other').create(title="Greasemonkey Hacks",
  196. published=datetime.date(2005, 11, 1))
  197. # Add a books to the m2m
  198. mark.book_set.add(grease)
  199. self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
  200. [u'Mark Pilgrim'])
  201. self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)),
  202. [u'Mark Pilgrim'])
  203. # Remove a book from the m2m
  204. mark.book_set.remove(grease)
  205. self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
  206. [u'Mark Pilgrim'])
  207. self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)),
  208. [])
  209. # Clear the books associated with mark
  210. mark.book_set.clear()
  211. self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
  212. [])
  213. self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)),
  214. [])
  215. # Create a book through the m2m interface
  216. mark.book_set.create(title="Dive into HTML5", published=datetime.date(2020, 1, 1))
  217. self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
  218. [])
  219. self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into HTML5').values_list('name', flat=True)),
  220. [u'Mark Pilgrim'])
  221. def test_m2m_cross_database_protection(self):
  222. "Operations that involve sharing M2M objects across databases raise an error"
  223. # Create a book and author on the default database
  224. pro = Book.objects.create(title="Pro Django",
  225. published=datetime.date(2008, 12, 16))
  226. marty = Person.objects.create(name="Marty Alchin")
  227. # Create a book and author on the other database
  228. dive = Book.objects.using('other').create(title="Dive into Python",
  229. published=datetime.date(2009, 5, 4))
  230. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  231. # Set a foreign key set with an object from a different database
  232. try:
  233. marty.book_set = [pro, dive]
  234. self.fail("Shouldn't be able to assign across databases")
  235. except ValueError:
  236. pass
  237. # Add to an m2m with an object from a different database
  238. try:
  239. marty.book_set.add(dive)
  240. self.fail("Shouldn't be able to assign across databases")
  241. except ValueError:
  242. pass
  243. # Set a m2m with an object from a different database
  244. try:
  245. marty.book_set = [pro, dive]
  246. self.fail("Shouldn't be able to assign across databases")
  247. except ValueError:
  248. pass
  249. # Add to a reverse m2m with an object from a different database
  250. try:
  251. dive.authors.add(marty)
  252. self.fail("Shouldn't be able to assign across databases")
  253. except ValueError:
  254. pass
  255. # Set a reverse m2m with an object from a different database
  256. try:
  257. dive.authors = [mark, marty]
  258. self.fail("Shouldn't be able to assign across databases")
  259. except ValueError:
  260. pass
  261. def test_m2m_deletion(self):
  262. "Cascaded deletions of m2m relations issue queries on the right database"
  263. # Create a book and author on the other database
  264. dive = Book.objects.using('other').create(title="Dive into Python",
  265. published=datetime.date(2009, 5, 4))
  266. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  267. dive.authors = [mark]
  268. # Check the initial state
  269. self.assertEqual(Person.objects.using('default').count(), 0)
  270. self.assertEqual(Book.objects.using('default').count(), 0)
  271. self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
  272. self.assertEqual(Person.objects.using('other').count(), 1)
  273. self.assertEqual(Book.objects.using('other').count(), 1)
  274. self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
  275. # Delete the object on the other database
  276. dive.delete(using='other')
  277. self.assertEqual(Person.objects.using('default').count(), 0)
  278. self.assertEqual(Book.objects.using('default').count(), 0)
  279. self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
  280. # The person still exists ...
  281. self.assertEqual(Person.objects.using('other').count(), 1)
  282. # ... but the book has been deleted
  283. self.assertEqual(Book.objects.using('other').count(), 0)
  284. # ... and the relationship object has also been deleted.
  285. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  286. # Now try deletion in the reverse direction. Set up the relation again
  287. dive = Book.objects.using('other').create(title="Dive into Python",
  288. published=datetime.date(2009, 5, 4))
  289. dive.authors = [mark]
  290. # Check the initial state
  291. self.assertEqual(Person.objects.using('default').count(), 0)
  292. self.assertEqual(Book.objects.using('default').count(), 0)
  293. self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
  294. self.assertEqual(Person.objects.using('other').count(), 1)
  295. self.assertEqual(Book.objects.using('other').count(), 1)
  296. self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
  297. # Delete the object on the other database
  298. mark.delete(using='other')
  299. self.assertEqual(Person.objects.using('default').count(), 0)
  300. self.assertEqual(Book.objects.using('default').count(), 0)
  301. self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
  302. # The person has been deleted ...
  303. self.assertEqual(Person.objects.using('other').count(), 0)
  304. # ... but the book still exists
  305. self.assertEqual(Book.objects.using('other').count(), 1)
  306. # ... and the relationship object has been deleted.
  307. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  308. def test_foreign_key_separation(self):
  309. "FK fields are constrained to a single database"
  310. # Create a book and author on the default database
  311. pro = Book.objects.create(title="Pro Django",
  312. published=datetime.date(2008, 12, 16))
  313. marty = Person.objects.create(name="Marty Alchin")
  314. george = Person.objects.create(name="George Vilches")
  315. # Create a book and author on the other database
  316. dive = Book.objects.using('other').create(title="Dive into Python",
  317. published=datetime.date(2009, 5, 4))
  318. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  319. chris = Person.objects.using('other').create(name="Chris Mills")
  320. # Save the author's favourite books
  321. pro.editor = george
  322. pro.save()
  323. dive.editor = chris
  324. dive.save()
  325. pro = Book.objects.using('default').get(title="Pro Django")
  326. self.assertEqual(pro.editor.name, "George Vilches")
  327. dive = Book.objects.using('other').get(title="Dive into Python")
  328. self.assertEqual(dive.editor.name, "Chris Mills")
  329. # Check that queries work across foreign key joins
  330. self.assertEqual(list(Person.objects.using('default').filter(edited__title='Pro Django').values_list('name', flat=True)),
  331. [u'George Vilches'])
  332. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Pro Django').values_list('name', flat=True)),
  333. [])
  334. self.assertEqual(list(Person.objects.using('default').filter(edited__title='Dive into Python').values_list('name', flat=True)),
  335. [])
  336. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
  337. [u'Chris Mills'])
  338. # Reget the objects to clear caches
  339. chris = Person.objects.using('other').get(name="Chris Mills")
  340. dive = Book.objects.using('other').get(title="Dive into Python")
  341. # Retrive related object by descriptor. Related objects should be database-baound
  342. self.assertEqual(list(chris.edited.values_list('title', flat=True)),
  343. [u'Dive into Python'])
  344. def test_foreign_key_reverse_operations(self):
  345. "FK reverse manipulations are all constrained to a single DB"
  346. dive = Book.objects.using('other').create(title="Dive into Python",
  347. published=datetime.date(2009, 5, 4))
  348. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  349. chris = Person.objects.using('other').create(name="Chris Mills")
  350. # Save the author relations
  351. dive.editor = chris
  352. dive.save()
  353. # Add a second book edited by chris
  354. html5 = Book.objects.using('other').create(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
  355. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
  356. [])
  357. chris.edited.add(html5)
  358. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
  359. [u'Chris Mills'])
  360. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
  361. [u'Chris Mills'])
  362. # Remove the second editor
  363. chris.edited.remove(html5)
  364. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
  365. [])
  366. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
  367. [u'Chris Mills'])
  368. # Clear all edited books
  369. chris.edited.clear()
  370. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
  371. [])
  372. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
  373. [])
  374. # Create an author through the m2m interface
  375. chris.edited.create(title='Dive into Water', published=datetime.date(2010, 3, 15))
  376. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
  377. [])
  378. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Water').values_list('name', flat=True)),
  379. [u'Chris Mills'])
  380. self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)),
  381. [])
  382. def test_foreign_key_cross_database_protection(self):
  383. "Operations that involve sharing FK objects across databases raise an error"
  384. # Create a book and author on the default database
  385. pro = Book.objects.create(title="Pro Django",
  386. published=datetime.date(2008, 12, 16))
  387. marty = Person.objects.create(name="Marty Alchin")
  388. # Create a book and author on the other database
  389. dive = Book.objects.using('other').create(title="Dive into Python",
  390. published=datetime.date(2009, 5, 4))
  391. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  392. # Set a foreign key with an object from a different database
  393. try:
  394. dive.editor = marty
  395. self.fail("Shouldn't be able to assign across databases")
  396. except ValueError:
  397. pass
  398. # Set a foreign key set with an object from a different database
  399. try:
  400. marty.edited = [pro, dive]
  401. self.fail("Shouldn't be able to assign across databases")
  402. except ValueError:
  403. pass
  404. # Add to a foreign key set with an object from a different database
  405. try:
  406. marty.edited.add(dive)
  407. self.fail("Shouldn't be able to assign across databases")
  408. except ValueError:
  409. pass
  410. # BUT! if you assign a FK object when the base object hasn't
  411. # been saved yet, you implicitly assign the database for the
  412. # base object.
  413. chris = Person(name="Chris Mills")
  414. html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
  415. # initially, no db assigned
  416. self.assertEqual(chris._state.db, None)
  417. self.assertEqual(html5._state.db, None)
  418. # old object comes from 'other', so the new object is set to use 'other'...
  419. dive.editor = chris
  420. html5.editor = mark
  421. self.assertEqual(chris._state.db, 'other')
  422. self.assertEqual(html5._state.db, 'other')
  423. # ... but it isn't saved yet
  424. self.assertEqual(list(Person.objects.using('other').values_list('name',flat=True)),
  425. [u'Mark Pilgrim'])
  426. self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)),
  427. [u'Dive into Python'])
  428. # When saved (no using required), new objects goes to 'other'
  429. chris.save()
  430. html5.save()
  431. self.assertEqual(list(Person.objects.using('default').values_list('name',flat=True)),
  432. [u'Marty Alchin'])
  433. self.assertEqual(list(Person.objects.using('other').values_list('name',flat=True)),
  434. [u'Chris Mills', u'Mark Pilgrim'])
  435. self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)),
  436. [u'Pro Django'])
  437. self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)),
  438. [u'Dive into HTML5', u'Dive into Python'])
  439. # This also works if you assign the FK in the constructor
  440. water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark)
  441. self.assertEqual(water._state.db, 'other')
  442. # ... but it isn't saved yet
  443. self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)),
  444. [u'Pro Django'])
  445. self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)),
  446. [u'Dive into HTML5', u'Dive into Python'])
  447. # When saved, the new book goes to 'other'
  448. water.save()
  449. self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)),
  450. [u'Pro Django'])
  451. self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)),
  452. [u'Dive into HTML5', u'Dive into Python', u'Dive into Water'])
  453. def test_foreign_key_deletion(self):
  454. "Cascaded deletions of Foreign Key relations issue queries on the right database"
  455. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  456. fido = Pet.objects.using('other').create(name="Fido", owner=mark)
  457. # Check the initial state
  458. self.assertEqual(Person.objects.using('default').count(), 0)
  459. self.assertEqual(Pet.objects.using('default').count(), 0)
  460. self.assertEqual(Person.objects.using('other').count(), 1)
  461. self.assertEqual(Pet.objects.using('other').count(), 1)
  462. # Delete the person object, which will cascade onto the pet
  463. mark.delete(using='other')
  464. self.assertEqual(Person.objects.using('default').count(), 0)
  465. self.assertEqual(Pet.objects.using('default').count(), 0)
  466. # Both the pet and the person have been deleted from the right database
  467. self.assertEqual(Person.objects.using('other').count(), 0)
  468. self.assertEqual(Pet.objects.using('other').count(), 0)
  469. def test_foreign_key_validation(self):
  470. "ForeignKey.validate() uses the correct database"
  471. mickey = Person.objects.using('other').create(name="Mickey")
  472. pluto = Pet.objects.using('other').create(name="Pluto", owner=mickey)
  473. self.assertEqual(None, pluto.full_clean())
  474. def test_o2o_separation(self):
  475. "OneToOne fields are constrained to a single database"
  476. # Create a user and profile on the default database
  477. alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com')
  478. alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate')
  479. # Create a user and profile on the other database
  480. bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com')
  481. bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog')
  482. # Retrieve related objects; queries should be database constrained
  483. alice = User.objects.using('default').get(username="alice")
  484. self.assertEqual(alice.userprofile.flavor, "chocolate")
  485. bob = User.objects.using('other').get(username="bob")
  486. self.assertEqual(bob.userprofile.flavor, "crunchy frog")
  487. # Check that queries work across joins
  488. self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='chocolate').values_list('username', flat=True)),
  489. [u'alice'])
  490. self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='chocolate').values_list('username', flat=True)),
  491. [])
  492. self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)),
  493. [])
  494. self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)),
  495. [u'bob'])
  496. # Reget the objects to clear caches
  497. alice_profile = UserProfile.objects.using('default').get(flavor='chocolate')
  498. bob_profile = UserProfile.objects.using('other').get(flavor='crunchy frog')
  499. # Retrive related object by descriptor. Related objects should be database-baound
  500. self.assertEqual(alice_profile.user.username, 'alice')
  501. self.assertEqual(bob_profile.user.username, 'bob')
  502. def test_o2o_cross_database_protection(self):
  503. "Operations that involve sharing FK objects across databases raise an error"
  504. # Create a user and profile on the default database
  505. alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com')
  506. # Create a user and profile on the other database
  507. bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com')
  508. # Set a one-to-one relation with an object from a different database
  509. alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate')
  510. try:
  511. bob.userprofile = alice_profile
  512. self.fail("Shouldn't be able to assign across databases")
  513. except ValueError:
  514. pass
  515. # BUT! if you assign a FK object when the base object hasn't
  516. # been saved yet, you implicitly assign the database for the
  517. # base object.
  518. bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog')
  519. new_bob_profile = UserProfile(flavor="spring surprise")
  520. charlie = User(username='charlie',email='charlie@example.com')
  521. charlie.set_unusable_password()
  522. # initially, no db assigned
  523. self.assertEqual(new_bob_profile._state.db, None)
  524. self.assertEqual(charlie._state.db, None)
  525. # old object comes from 'other', so the new object is set to use 'other'...
  526. new_bob_profile.user = bob
  527. charlie.userprofile = bob_profile
  528. self.assertEqual(new_bob_profile._state.db, 'other')
  529. self.assertEqual(charlie._state.db, 'other')
  530. # ... but it isn't saved yet
  531. self.assertEqual(list(User.objects.using('other').values_list('username',flat=True)),
  532. [u'bob'])
  533. self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
  534. [u'crunchy frog'])
  535. # When saved (no using required), new objects goes to 'other'
  536. charlie.save()
  537. bob_profile.save()
  538. new_bob_profile.save()
  539. self.assertEqual(list(User.objects.using('default').values_list('username',flat=True)),
  540. [u'alice'])
  541. self.assertEqual(list(User.objects.using('other').values_list('username',flat=True)),
  542. [u'bob', u'charlie'])
  543. self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
  544. [u'chocolate'])
  545. self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
  546. [u'crunchy frog', u'spring surprise'])
  547. # This also works if you assign the O2O relation in the constructor
  548. denise = User.objects.db_manager('other').create_user('denise','denise@example.com')
  549. denise_profile = UserProfile(flavor="tofu", user=denise)
  550. self.assertEqual(denise_profile._state.db, 'other')
  551. # ... but it isn't saved yet
  552. self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
  553. [u'chocolate'])
  554. self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
  555. [u'crunchy frog', u'spring surprise'])
  556. # When saved, the new profile goes to 'other'
  557. denise_profile.save()
  558. self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
  559. [u'chocolate'])
  560. self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
  561. [u'crunchy frog', u'spring surprise', u'tofu'])
  562. def test_generic_key_separation(self):
  563. "Generic fields are constrained to a single database"
  564. # Create a book and author on the default database
  565. pro = Book.objects.create(title="Pro Django",
  566. published=datetime.date(2008, 12, 16))
  567. review1 = Review.objects.create(source="Python Monthly", content_object=pro)
  568. # Create a book and author on the other database
  569. dive = Book.objects.using('other').create(title="Dive into Python",
  570. published=datetime.date(2009, 5, 4))
  571. review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
  572. review1 = Review.objects.using('default').get(source="Python Monthly")
  573. self.assertEqual(review1.content_object.title, "Pro Django")
  574. review2 = Review.objects.using('other').get(source="Python Weekly")
  575. self.assertEqual(review2.content_object.title, "Dive into Python")
  576. # Reget the objects to clear caches
  577. dive = Book.objects.using('other').get(title="Dive into Python")
  578. # Retrive related object by descriptor. Related objects should be database-bound
  579. self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)),
  580. [u'Python Weekly'])
  581. def test_generic_key_reverse_operations(self):
  582. "Generic reverse manipulations are all constrained to a single DB"
  583. dive = Book.objects.using('other').create(title="Dive into Python",
  584. published=datetime.date(2009, 5, 4))
  585. temp = Book.objects.using('other').create(title="Temp",
  586. published=datetime.date(2009, 5, 4))
  587. review1 = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
  588. review2 = Review.objects.using('other').create(source="Python Monthly", content_object=temp)
  589. self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
  590. [])
  591. self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  592. [u'Python Weekly'])
  593. # Add a second review
  594. dive.reviews.add(review2)
  595. self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
  596. [])
  597. self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  598. [u'Python Monthly', u'Python Weekly'])
  599. # Remove the second author
  600. dive.reviews.remove(review1)
  601. self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
  602. [])
  603. self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  604. [u'Python Monthly'])
  605. # Clear all reviews
  606. dive.reviews.clear()
  607. self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
  608. [])
  609. self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  610. [])
  611. # Create an author through the generic interface
  612. dive.reviews.create(source='Python Daily')
  613. self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
  614. [])
  615. self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  616. [u'Python Daily'])
  617. def test_generic_key_cross_database_protection(self):
  618. "Operations that involve sharing generic key objects across databases raise an error"
  619. # Create a book and author on the default database
  620. pro = Book.objects.create(title="Pro Django",
  621. published=datetime.date(2008, 12, 16))
  622. review1 = Review.objects.create(source="Python Monthly", content_object=pro)
  623. # Create a book and author on the other database
  624. dive = Book.objects.using('other').create(title="Dive into Python",
  625. published=datetime.date(2009, 5, 4))
  626. review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
  627. # Set a foreign key with an object from a different database
  628. try:
  629. review1.content_object = dive
  630. self.fail("Shouldn't be able to assign across databases")
  631. except ValueError:
  632. pass
  633. # Add to a foreign key set with an object from a different database
  634. try:
  635. dive.reviews.add(review1)
  636. self.fail("Shouldn't be able to assign across databases")
  637. except ValueError:
  638. pass
  639. # BUT! if you assign a FK object when the base object hasn't
  640. # been saved yet, you implicitly assign the database for the
  641. # base object.
  642. review3 = Review(source="Python Daily")
  643. # initially, no db assigned
  644. self.assertEqual(review3._state.db, None)
  645. # Dive comes from 'other', so review3 is set to use 'other'...
  646. review3.content_object = dive
  647. self.assertEqual(review3._state.db, 'other')
  648. # ... but it isn't saved yet
  649. self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
  650. [u'Python Monthly'])
  651. self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source',flat=True)),
  652. [u'Python Weekly'])
  653. # When saved, John goes to 'other'
  654. review3.save()
  655. self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
  656. [u'Python Monthly'])
  657. self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source',flat=True)),
  658. [u'Python Daily', u'Python Weekly'])
  659. def test_generic_key_deletion(self):
  660. "Cascaded deletions of Generic Key relations issue queries on the right database"
  661. dive = Book.objects.using('other').create(title="Dive into Python",
  662. published=datetime.date(2009, 5, 4))
  663. review = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
  664. # Check the initial state
  665. self.assertEqual(Book.objects.using('default').count(), 0)
  666. self.assertEqual(Review.objects.using('default').count(), 0)
  667. self.assertEqual(Book.objects.using('other').count(), 1)
  668. self.assertEqual(Review.objects.using('other').count(), 1)
  669. # Delete the Book object, which will cascade onto the pet
  670. dive.delete(using='other')
  671. self.assertEqual(Book.objects.using('default').count(), 0)
  672. self.assertEqual(Review.objects.using('default').count(), 0)
  673. # Both the pet and the person have been deleted from the right database
  674. self.assertEqual(Book.objects.using('other').count(), 0)
  675. self.assertEqual(Review.objects.using('other').count(), 0)
  676. def test_ordering(self):
  677. "get_next_by_XXX commands stick to a single database"
  678. pro = Book.objects.create(title="Pro Django",
  679. published=datetime.date(2008, 12, 16))
  680. dive = Book.objects.using('other').create(title="Dive into Python",
  681. published=datetime.date(2009, 5, 4))
  682. learn = Book.objects.using('other').create(title="Learning Python",
  683. published=datetime.date(2008, 7, 16))
  684. self.assertEqual(learn.get_next_by_published().title, "Dive into Python")
  685. self.assertEqual(dive.get_previous_by_published().title, "Learning Python")
  686. def test_raw(self):
  687. "test the raw() method across databases"
  688. dive = Book.objects.using('other').create(title="Dive into Python",
  689. published=datetime.date(2009, 5, 4))
  690. val = Book.objects.db_manager("other").raw('SELECT id FROM multiple_database_book')
  691. self.assertEqual(map(lambda o: o.pk, val), [dive.pk])
  692. val = Book.objects.raw('SELECT id FROM multiple_database_book').using('other')
  693. self.assertEqual(map(lambda o: o.pk, val), [dive.pk])
  694. def test_select_related(self):
  695. "Database assignment is retained if an object is retrieved with select_related()"
  696. # Create a book and author on the other database
  697. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  698. dive = Book.objects.using('other').create(title="Dive into Python",
  699. published=datetime.date(2009, 5, 4),
  700. editor=mark)
  701. # Retrieve the Person using select_related()
  702. book = Book.objects.using('other').select_related('editor').get(title="Dive into Python")
  703. # The editor instance should have a db state
  704. self.assertEqual(book.editor._state.db, 'other')
  705. def test_subquery(self):
  706. """Make sure as_sql works with subqueries and master/slave."""
  707. sub = Person.objects.using('other').filter(name='fff')
  708. qs = Book.objects.filter(editor__in=sub)
  709. # When you call __str__ on the query object, it doesn't know about using
  710. # so it falls back to the default. If the subquery explicitly uses a
  711. # different database, an error should be raised.
  712. self.assertRaises(ValueError, str, qs.query)
  713. # Evaluating the query shouldn't work, either
  714. try:
  715. for obj in qs:
  716. pass
  717. self.fail('Iterating over query should raise ValueError')
  718. except ValueError:
  719. pass
  720. def test_related_manager(self):
  721. "Related managers return managers, not querysets"
  722. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  723. # extra_arg is removed by the BookManager's implementation of
  724. # create(); but the BookManager's implementation won't get called
  725. # unless edited returns a Manager, not a queryset
  726. mark.book_set.create(title="Dive into Python",
  727. published=datetime.date(2009, 5, 4),
  728. extra_arg=True)
  729. mark.book_set.get_or_create(title="Dive into Python",
  730. published=datetime.date(2009, 5, 4),
  731. extra_arg=True)
  732. mark.edited.create(title="Dive into Water",
  733. published=datetime.date(2009, 5, 4),
  734. extra_arg=True)
  735. mark.edited.get_or_create(title="Dive into Water",
  736. published=datetime.date(2009, 5, 4),
  737. extra_arg=True)
  738. class TestRouter(object):
  739. # A test router. The behaviour is vaguely master/slave, but the
  740. # databases aren't assumed to propagate changes.
  741. def db_for_read(self, model, instance=None, **hints):
  742. if instance:
  743. return instance._state.db or 'other'
  744. return 'other'
  745. def db_for_write(self, model, **hints):
  746. return DEFAULT_DB_ALIAS
  747. def allow_relation(self, obj1, obj2, **hints):
  748. return obj1._state.db in ('default', 'other') and obj2._state.db in ('default', 'other')
  749. def allow_syncdb(self, db, model):
  750. return True
  751. class AuthRouter(object):
  752. """A router to control all database operations on models in
  753. the contrib.auth application"""
  754. def db_for_read(self, model, **hints):
  755. "Point all read operations on auth models to 'default'"
  756. if model._meta.app_label == 'auth':
  757. # We use default here to ensure we can tell the difference
  758. # between a read request and a write request for Auth objects
  759. return 'default'
  760. return None
  761. def db_for_write(self, model, **hints):
  762. "Point all operations on auth models to 'other'"
  763. if model._meta.app_label == 'auth':
  764. return 'other'
  765. return None
  766. def allow_relation(self, obj1, obj2, **hints):
  767. "Allow any relation if a model in Auth is involved"
  768. if obj1._meta.app_label == 'auth' or obj2._meta.app_label == 'auth':
  769. return True
  770. return None
  771. def allow_syncdb(self, db, model):
  772. "Make sure the auth app only appears on the 'other' db"
  773. if db == 'other':
  774. return model._meta.app_label == 'auth'
  775. elif model._meta.app_label == 'auth':
  776. return False
  777. return None
  778. class WriteRouter(object):
  779. # A router that only expresses an opinion on writes
  780. def db_for_write(self, model, **hints):
  781. return 'writer'
  782. class RouterTestCase(TestCase):
  783. multi_db = True
  784. def setUp(self):
  785. # Make the 'other' database appear to be a slave of the 'default'
  786. self.old_routers = router.routers
  787. router.routers = [TestRouter()]
  788. def tearDown(self):
  789. # Restore the 'other' database as an independent database
  790. router.routers = self.old_routers
  791. def test_db_selection(self):
  792. "Check that querysets obey the router for db suggestions"
  793. self.assertEqual(Book.objects.db, 'other')
  794. self.assertEqual(Book.objects.all().db, 'other')
  795. self.assertEqual(Book.objects.using('default').db, 'default')
  796. self.assertEqual(Book.objects.db_manager('default').db, 'default')
  797. self.assertEqual(Book.objects.db_manager('default').all().db, 'default')
  798. def test_syncdb_selection(self):
  799. "Synchronization behaviour is predicatable"
  800. self.assertTrue(router.allow_syncdb('default', User))
  801. self.assertTrue(router.allow_syncdb('default', Book))
  802. self.assertTrue(router.allow_syncdb('other', User))
  803. self.assertTrue(router.allow_syncdb('other', Book))
  804. # Add the auth router to the chain.
  805. # TestRouter is a universal synchronizer, so it should have no effect.
  806. router.routers = [TestRouter(), AuthRouter()]
  807. self.assertTrue(router.allow_syncdb('default', User))
  808. self.assertTrue(router.allow_syncdb('default', Book))
  809. self.assertTrue(router.allow_syncdb('other', User))
  810. self.assertTrue(router.allow_syncdb('other', Book))
  811. # Now check what happens if the router order is the other way around
  812. router.routers = [AuthRouter(), TestRouter()]
  813. self.assertFalse(router.allow_syncdb('default', User))
  814. self.assertTrue(router.allow_syncdb('default', Book))
  815. self.assertTrue(router.allow_syncdb('other', User))
  816. self.assertFalse(router.allow_syncdb('other', Book))
  817. def test_partial_router(self):
  818. "A router can choose to implement a subset of methods"
  819. dive = Book.objects.using('other').create(title="Dive into Python",
  820. published=datetime.date(2009, 5, 4))
  821. # First check the baseline behaviour
  822. self.assertEqual(router.db_for_read(User), 'other')
  823. self.assertEqual(router.db_for_read(Book), 'other')
  824. self.assertEqual(router.db_for_write(User), 'default')
  825. self.assertEqual(router.db_for_write(Book), 'default')
  826. self.assertTrue(router.allow_relation(dive, dive))
  827. self.assertTrue(router.allow_syncdb('default', User))
  828. self.assertTrue(router.allow_syncdb('default', Book))
  829. router.routers = [WriteRouter(), AuthRouter(), TestRouter()]
  830. self.assertEqual(router.db_for_read(User), 'default')
  831. self.assertEqual(router.db_for_read(Book), 'other')
  832. self.assertEqual(router.db_for_write(User), 'writer')
  833. self.assertEqual(router.db_for_write(Book), 'writer')
  834. self.assertTrue(router.allow_relatio

Large files files are truncated, but you can click here to view the full file