PageRenderTime 59ms CodeModel.GetById 18ms RepoModel.GetById 0ms 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
  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_relation(dive, dive))
  835. self.assertFalse(router.allow_syncdb('default', User))
  836. self.assertTrue(router.allow_syncdb('default', Book))
  837. def test_database_routing(self):
  838. marty = Person.objects.using('default').create(name="Marty Alchin")
  839. pro = Book.objects.using('default').create(title="Pro Django",
  840. published=datetime.date(2008, 12, 16),
  841. editor=marty)
  842. pro.authors = [marty]
  843. # Create a book and author on the other database
  844. dive = Book.objects.using('other').create(title="Dive into Python",
  845. published=datetime.date(2009, 5, 4))
  846. # An update query will be routed to the default database
  847. Book.objects.filter(title='Pro Django').update(pages=200)
  848. try:
  849. # By default, the get query will be directed to 'other'
  850. Book.objects.get(title='Pro Django')
  851. self.fail("Shouldn't be able to find the book")
  852. except Book.DoesNotExist:
  853. pass
  854. # But the same query issued explicitly at a database will work.
  855. pro = Book.objects.using('default').get(title='Pro Django')
  856. # Check that the update worked.
  857. self.assertEqual(pro.pages, 200)
  858. # An update query with an explicit using clause will be routed
  859. # to the requested database.
  860. Book.objects.using('other').filter(title='Dive into Python').update(pages=300)
  861. self.assertEqual(Book.objects.get(title='Dive into Python').pages, 300)
  862. # Related object queries stick to the same database
  863. # as the original object, regardless of the router
  864. self.assertEqual(list(pro.authors.values_list('name', flat=True)), [u'Marty Alchin'])
  865. self.assertEqual(pro.editor.name, u'Marty Alchin')
  866. # get_or_create is a special case. The get needs to be targetted at
  867. # the write database in order to avoid potential transaction
  868. # consistency problems
  869. book, created = Book.objects.get_or_create(title="Pro Django")
  870. self.assertFalse(created)
  871. book, created = Book.objects.get_or_create(title="Dive Into Python",
  872. defaults={'published':datetime.date(2009, 5, 4)})
  873. self.assertTrue(created)
  874. # Check the head count of objects
  875. self.assertEqual(Book.objects.using('default').count(), 2)
  876. self.assertEqual(Book.objects.using('other').count(), 1)
  877. # If a database isn't specified, the read database is used
  878. self.assertEqual(Book.objects.count(), 1)
  879. # A delete query will also be routed to the default database
  880. Book.objects.filter(pages__gt=150).delete()
  881. # The default database has lost the book.
  882. self.assertEqual(Book.objects.using('default').count(), 1)
  883. self.assertEqual(Book.objects.using('other').count(), 1)
  884. def test_foreign_key_cross_database_protection(self):
  885. "Foreign keys can cross databases if they two databases have a common source"
  886. # Create a book and author on the default database
  887. pro = Book.objects.using('default').create(title="Pro Django",
  888. published=datetime.date(2008, 12, 16))
  889. marty = Person.objects.using('default').create(name="Marty Alchin")
  890. # Create a book and author on the other database
  891. dive = Book.objects.using('other').create(title="Dive into Python",
  892. published=datetime.date(2009, 5, 4))
  893. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  894. # Set a foreign key with an object from a different database
  895. try:
  896. dive.editor = marty
  897. except ValueError:
  898. self.fail("Assignment across master/slave databases with a common source should be ok")
  899. # Database assignments of original objects haven't changed...
  900. self.assertEqual(marty._state.db, 'default')
  901. self.assertEqual(pro._state.db, 'default')
  902. self.assertEqual(dive._state.db, 'other')
  903. self.assertEqual(mark._state.db, 'other')
  904. # ... but they will when the affected object is saved.
  905. dive.save()
  906. self.assertEqual(dive._state.db, 'default')
  907. # ...and the source database now has a copy of any object saved
  908. try:
  909. Book.objects.using('default').get(title='Dive into Python').delete()
  910. except Book.DoesNotExist:
  911. self.fail('Source database should have a copy of saved object')
  912. # This isn't a real master-slave database, so restore the original from other
  913. dive = Book.objects.using('other').get(title='Dive into Python')
  914. self.assertEqual(dive._state.db, 'other')
  915. # Set a foreign key set with an object from a different database
  916. try:
  917. marty.edited = [pro, dive]
  918. except ValueError:
  919. self.fail("Assignment across master/slave databases with a common source should be ok")
  920. # Assignment implies a save, so database assignments of original objects have changed...
  921. self.assertEqual(marty._state.db, 'default')
  922. self.assertEqual(pro._state.db, 'default')
  923. self.assertEqual(dive._state.db, 'default')
  924. self.assertEqual(mark._state.db, 'other')
  925. # ...and the source database now has a copy of any object saved
  926. try:
  927. Book.objects.using('default').get(title='Dive into Python').delete()
  928. except Book.DoesNotExist:
  929. self.fail('Source database should have a copy of saved object')
  930. # This isn't a real master-slave database, so restore the original from other
  931. dive = Book.objects.using('other').get(title='Dive into Python')
  932. self.assertEqual(dive._state.db, 'other')
  933. # Add to a foreign key set with an object from a different database
  934. try:
  935. marty.edited.add(dive)
  936. except ValueError:
  937. self.fail("Assignment across master/slave databases with a common source should be ok")
  938. # Add implies a save, so database assignments of original objects have changed...
  939. self.assertEqual(marty._state.db, 'default')
  940. self.assertEqual(pro._state.db, 'default')
  941. self.assertEqual(dive._state.db, 'default')
  942. self.assertEqual(mark._state.db, 'other')
  943. # ...and the source database now has a copy of any object saved
  944. try:
  945. Book.objects.using('default').get(title='Dive into Python').delete()
  946. except Book.DoesNotExist:
  947. self.fail('Source database should have a copy of saved object')
  948. # This isn't a real master-slave database, so restore the original from other
  949. dive = Book.objects.using('other').get(title='Dive into Python')
  950. # If you assign a FK object when the base object hasn't
  951. # been saved yet, you implicitly assign the database for the
  952. # base object.
  953. chris = Person(name="Chris Mills")
  954. html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
  955. # initially, no db assigned
  956. self.assertEqual(chris._state.db, None)
  957. self.assertEqual(html5._state.db, None)
  958. # old object comes from 'other', so the new object is set to use the
  959. # source of 'other'...
  960. self.assertEqual(dive._state.db, 'other')
  961. dive.editor = chris
  962. html5.editor = mark
  963. self.assertEqual(dive._state.db, 'other')
  964. self.assertEqual(mark._state.db, 'other')
  965. self.assertEqual(chris._state.db, 'default')
  966. self.assertEqual(html5._state.db, 'default')
  967. # This also works if you assign the FK in the constructor
  968. water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark)
  969. self.assertEqual(water._state.db, 'default')
  970. # If you create an object through a FK relation, it will be
  971. # written to the write database, even if the original object
  972. # was on the read database
  973. cheesecake = mark.edited.create(title='Dive into Cheesecake', published=datetime.date(2010, 3, 15))
  974. self.assertEqual(cheesecake._state.db, 'default')
  975. # Same goes for get_or_create, regardless of whether getting or creating
  976. cheesecake, created = mark.edited.get_or_create(title='Dive into Cheesecake', published=datetime.date(2010, 3, 15))
  977. self.assertEqual(cheesecake._state.db, 'default')
  978. puddles, created = mark.edited.get_or_create(title='Dive into Puddles', published=datetime.date(2010, 3, 15))
  979. self.assertEqual(puddles._state.db, 'default')
  980. def test_m2m_cross_database_protection(self):
  981. "M2M relations can cross databases if the database share a source"
  982. # Create books and authors on the inverse to the usual database
  983. pro = Book.objects.using('other').create(pk=1, title="Pro Django",
  984. published=datetime.date(2008, 12, 16))
  985. marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
  986. dive = Book.objects.using('default').create(pk=2, title="Dive into Python",
  987. published=datetime.date(2009, 5, 4))
  988. mark = Person.objects.using('default').create(pk=2, name="Mark Pilgrim")
  989. # Now save back onto the usual database.
  990. # This simulates master/slave - the objects exist on both database,
  991. # but the _state.db is as it is for all other tests.
  992. pro.save(using='default')
  993. marty.save(using='default')
  994. dive.save(using='other')
  995. mark.save(using='other')
  996. # Check that we have 2 of both types of object on both databases
  997. self.assertEqual(Book.objects.using('default').count(), 2)
  998. self.assertEqual(Book.objects.using('other').count(), 2)
  999. self.assertEqual(Person.objects.using('default').count(), 2)
  1000. self.assertEqual(Person.objects.using('other').count(), 2)
  1001. # Set a m2m set with an object from a different database
  1002. try:
  1003. marty.book_set = [pro, dive]
  1004. except ValueError:
  1005. self.fail("Assignment across master/slave databases with a common source should be ok")
  1006. # Database assignments don't change
  1007. self.assertEqual(marty._state.db, 'default')
  1008. self.assertEqual(pro._state.db, 'default')
  1009. self.assertEqual(dive._state.db, 'other')
  1010. self.assertEqual(mark._state.db, 'other')
  1011. # All m2m relations should be saved on the default database
  1012. self.assertEqual(Book.authors.through.objects.using('default').count(), 2)
  1013. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  1014. # Reset relations
  1015. Book.authors.through.objects.using('default').delete()
  1016. # Add to an m2m with an object from a different database
  1017. try:
  1018. marty.book_set.add(dive)
  1019. except ValueError:
  1020. self.fail("Assignment across master/slave databases with a common source should be ok")
  1021. # Database assignments don't change
  1022. self.assertEqual(marty._state.db, 'default')
  1023. self.assertEqual(pro._state.db, 'default')
  1024. self.assertEqual(dive._state.db, 'other')
  1025. self.assertEqual(mark._state.db, 'other')
  1026. # All m2m relations should be saved on the default database
  1027. self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
  1028. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  1029. # Reset relations
  1030. Book.authors.through.objects.using('default').delete()
  1031. # Set a reverse m2m with an object from a different database
  1032. try:
  1033. dive.authors = [mark, marty]
  1034. except ValueError:
  1035. self.fail("Assignment across master/slave databases with a common source should be ok")
  1036. # Database assignments don't change
  1037. self.assertEqual(marty._state.db, 'default')
  1038. self.assertEqual(pro._state.db, 'default')
  1039. self.assertEqual(dive._state.db, 'other')
  1040. self.assertEqual(mark._state.db, 'other')
  1041. # All m2m relations should be saved on the default database
  1042. self.assertEqual(Book.authors.through.objects.using('default').count(), 2)
  1043. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  1044. # Reset relations
  1045. Book.authors.through.objects.using('default').delete()
  1046. self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
  1047. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  1048. # Add to a reverse m2m with an object from a different database
  1049. try:
  1050. dive.authors.add(marty)
  1051. except ValueError:
  1052. self.fail("Assignment across master/slave databases with a common source should be ok")
  1053. # Database assignments don't change
  1054. self.assertEqual(marty._state.db, 'default')
  1055. self.assertEqual(pro._state.db, 'default')
  1056. self.assertEqual(dive._state.db, 'other')
  1057. self.assertEqual(mark._state.db, 'other')
  1058. # All m2m relations should be saved on the default database
  1059. self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
  1060. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  1061. # If you create an object through a M2M relation, it will be
  1062. # written to the write database, even if the original object
  1063. # was on the read database
  1064. alice = dive.authors.create(name='Alice')
  1065. self.assertEqual(alice._state.db, 'default')
  1066. # Same goes for get_or_create, regardless of whether getting or creating
  1067. alice, created = dive.authors.get_or_create(name='Alice')
  1068. self.assertEqual(alice._state.db, 'default')
  1069. bob, created = dive.authors.get_or_create(name='Bob')
  1070. self.assertEqual(bob._state.db, 'default')
  1071. def test_o2o_cross_database_protection(self):
  1072. "Operations that involve sharing FK objects across databases raise an error"
  1073. # Create a user and profile on the default database
  1074. alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com')
  1075. # Create a user and profile on the other database
  1076. bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com')
  1077. # Set a one-to-one relation with an object from a different database
  1078. alice_profile = UserProfile.objects.create(user=alice, flavor='chocolate')
  1079. try:
  1080. bob.userprofile = alice_profile
  1081. except ValueError:
  1082. self.fail("Assignment across master/slave databases with a common source should be ok")
  1083. # Database assignments of original objects haven't changed...
  1084. self.assertEqual(alice._state.db, 'default')
  1085. self.assertEqual(alice_profile._state.db, 'default')
  1086. self.assertEqual(bob._state.db, 'other')
  1087. # ... but they will when the affected object is saved.
  1088. bob.save()
  1089. self.assertEqual(bob._state.db, 'default')
  1090. def test_generic_key_cross_database_protection(self):
  1091. "Generic Key operations can span databases if they share a source"
  1092. # Create a book and author on the default database
  1093. pro = Book.objects.using('default'
  1094. ).create(title="Pro Django", published=datetime.date(2008, 12, 16))
  1095. review1 = Review.objects.using('default'
  1096. ).create(source="Python Monthly", content_object=pro)
  1097. # Create a book and author on the other database
  1098. dive = Book.objects.using('other'
  1099. ).create(title="Dive into Python", published=datetime.date(2009, 5, 4))
  1100. review2 = Review.objects.using('other'
  1101. ).create(source="Python Weekly", content_object=dive)
  1102. # Set a generic foreign key with an object from a different database
  1103. try:
  1104. review1.content_object = dive
  1105. except ValueError:
  1106. self.fail("Assignment across master/slave databases with a common source should be ok")
  1107. # Database assignments of original objects haven't changed...
  1108. self.assertEqual(pro._state.db, 'default')
  1109. self.assertEqual(review1._state.db, 'default')
  1110. self.assertEqual(dive._state.db, 'other')
  1111. self.assertEqual(review2._state.db, 'other')
  1112. # ... but they will when the affected object is saved.
  1113. dive.save()
  1114. self.assertEqual(review1._state.db, 'default')
  1115. self.assertEqual(dive._state.db, 'default')
  1116. # ...and the source database now has a copy of any object saved
  1117. try:
  1118. Book.objects.using('default').get(title='Dive into Python').delete()
  1119. except Book.DoesNotExist:
  1120. self.fail('Source database should have a copy of saved object')
  1121. # This isn't a real master-slave database, so restore the original from other
  1122. dive = Book.objects.using('other').get(title='Dive into Python')
  1123. self.assertEqual(dive._state.db, 'other')
  1124. # Add to a generic foreign key set with an object from a different database
  1125. try:
  1126. dive.reviews.add(review1)
  1127. except ValueError:
  1128. self.fail("Assignment across master/slave databases with a common source should be ok")
  1129. # Database assignments of original objects haven't changed...
  1130. self.assertEqual(pro._state.db, 'default')
  1131. self.assertEqual(review1._state.db, 'default')
  1132. self.assertEqual(dive._state.db, 'other')
  1133. self.assertEqual(review2._state.db, 'other')
  1134. # ... but they will when the affected object is saved.
  1135. dive.save()
  1136. self.assertEqual(dive._state.db, 'default')
  1137. # ...and the source database now has a copy of any object saved
  1138. try:
  1139. Book.objects.using('default').get(title='Dive into Python').delete()
  1140. except Book.DoesNotExist:
  1141. self.fail('Source database should have a copy of saved object')
  1142. # BUT! if you assign a FK object when the base object hasn't
  1143. # been saved yet, you implicitly assign the database for the
  1144. # base object.
  1145. review3 = Review(source="Python Daily")
  1146. # initially, no db assigned
  1147. self.assertEqual(review3._state.db, None)
  1148. # Dive comes from 'other', so review3 is set to use the source of 'other'...
  1149. review3.content_object = dive
  1150. self.assertEqual(review3._state.db, 'default')
  1151. # If you create an object through a M2M relation, it will be
  1152. # written to the write database, even if the original object
  1153. # was on the read database
  1154. dive = Book.objects.using('other').get(title='Dive into Python')
  1155. nyt = dive.reviews.create(source="New York Times", content_object=dive)
  1156. self.assertEqual(nyt._state.db, 'default')
  1157. def test_m2m_managers(self):
  1158. "M2M relations are represented by managers, and can be controlled like managers"
  1159. pro = Book.objects.using('other').create(pk=1, title="Pro Django",
  1160. published=datetime.date(2008, 12, 16))
  1161. marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
  1162. pro.authors = [marty]
  1163. self.assertEqual(pro.authors.db, 'other')
  1164. self.assertEqual(pro.authors.db_manager('default').db, 'default')
  1165. self.assertEqual(pro.authors.db_manager('default').all().db, 'default')
  1166. self.assertEqual(marty.book_set.db, 'other')
  1167. self.assertEqual(marty.book_set.db_manager('default').db, 'default')
  1168. self.assertEqual(marty.book_set.db_manager('default').all().db, 'default')
  1169. def test_foreign_key_managers(self):
  1170. "FK reverse relations are represented by managers, and can be controlled like managers"
  1171. marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
  1172. pro = Book.objects.using('other').create(pk=1, title="Pro Django",
  1173. published=datetime.date(2008, 12, 16),
  1174. editor=marty)
  1175. self.assertEqual(marty.edited.db, 'other')
  1176. self.assertEqual(marty.edited.db_manager('default').db, 'default')
  1177. self.assertEqual(marty.edited.db_manager('default').all().db, 'default')
  1178. def test_generic_key_managers(self):
  1179. "Generic key relations are represented by managers, and can be controlled like managers"
  1180. pro = Book.objects.using('other').create(title="Pro Django",
  1181. published=datetime.date(2008, 12, 16))
  1182. review1 = Review.objects.using('other').create(source="Python Monthly",
  1183. content_object=pro)
  1184. self.assertEqual(pro.reviews.db, 'other')
  1185. self.assertEqual(pro.reviews.db_manager('default').db, 'default')
  1186. self.assertEqual(pro.reviews.db_manager('default').all().db, 'default')
  1187. def test_subquery(self):
  1188. """Make sure as_sql works with subqueries and master/slave."""
  1189. # Create a book and author on the other database
  1190. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  1191. dive = Book.objects.using('other').create(title="Dive into Python",
  1192. published=datetime.date(2009, 5, 4),
  1193. editor=mark)
  1194. sub = Person.objects.filter(name='Mark Pilgrim')
  1195. qs = Book.objects.filter(editor__in=sub)
  1196. # When you call __str__ on the query object, it doesn't know about using
  1197. # so it falls back to the default. Don't let routing instructions
  1198. # force the subquery to an incompatible database.
  1199. str(qs.query)
  1200. # If you evaluate the query, it should work, running on 'other'
  1201. self.assertEqual(list(qs.values_list('title', flat=True)), [u'Dive into Python'])
  1202. class AuthTestCase(TestCase):
  1203. multi_db = True
  1204. def setUp(self):
  1205. # Make the 'other' database appear to be a slave of the 'default'
  1206. self.old_routers = router.routers
  1207. router.routers = [AuthRouter()]
  1208. def tearDown(self):
  1209. # Restore the 'other' database as an independent database
  1210. router.routers = self.old_routers
  1211. def test_auth_manager(self):
  1212. "The methods on the auth manager obey database hints"
  1213. # Create one user using default allocation policy
  1214. User.objects.create_user('alice', 'alice@example.com')
  1215. # Create another user, explicitly specifying the database
  1216. User.objects.db_manager('default').create_user('bob', 'bob@example.com')
  1217. # The second user only exists on the other database
  1218. alice = User.objects.using('other').get(username='alice')
  1219. self.assertEqual(alice.username, 'alice')
  1220. self.assertEqual(alice._state.db, 'other')
  1221. self.assertRaises(User.DoesNotExist, User.objects.using('default').get, username='alice')
  1222. # The second user only exists on the default database
  1223. bob = User.objects.using('default').get(username='bob')
  1224. self.assertEqual(bob.username, 'bob')
  1225. self.assertEqual(bob._state.db, 'default')
  1226. self.assertRaises(User.DoesNotExist, User.objects.using('other').get, username='bob')
  1227. # That is... there is one user on each database
  1228. self.assertEqual(User.objects.using('default').count(), 1)
  1229. self.assertEqual(User.objects.using('other').count(), 1)
  1230. def test_dumpdata(self):
  1231. "Check that dumpdata honors allow_syncdb restrictions on the router"
  1232. User.objects.create_user('alice', 'alice@example.com')
  1233. User.objects.db_manager('default').create_user('bob', 'bob@example.com')
  1234. # Check that dumping the default database doesn't try to include auth
  1235. # because allow_syncdb prohibits auth on default
  1236. new_io = StringIO()
  1237. management.call_command('dumpdata', 'auth', format='json', database='default', stdout=new_io)
  1238. command_output = new_io.getvalue().strip()
  1239. self.assertEqual(command_output, '[]')
  1240. # Check that dumping the other database does include auth
  1241. new_io = StringIO()
  1242. management.call_command('dumpdata', 'auth', format='json', database='other', stdout=new_io)
  1243. command_output = new_io.getvalue().strip()
  1244. self.assertTrue('"email": "alice@example.com",' in command_output)
  1245. _missing = object()
  1246. class UserProfileTestCase(TestCase):
  1247. def setUp(self):
  1248. self.old_auth_profile_module = getattr(settings, 'AUTH_PROFILE_MODULE', _missing)
  1249. settings.AUTH_PROFILE_MODULE = 'multiple_database.UserProfile'
  1250. def tearDown(self):
  1251. if self.old_auth_profile_module is _missing:
  1252. del settings.AUTH_PROFILE_MODULE
  1253. else:
  1254. settings.AUTH_PROFILE_MODULE = self.old_auth_profile_module
  1255. def test_user_profiles(self):
  1256. alice = User.objects.create_user('alice', 'alice@example.com')
  1257. bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com')
  1258. alice_profile = UserProfile(user=alice, flavor='chocolate')
  1259. alice_profile.save()
  1260. bob_profile = UserProfile(user=bob, flavor='crunchy frog')
  1261. bob_profile.save()
  1262. self.assertEqual(alice.get_profile().flavor, 'chocolate')
  1263. self.assertEqual(bob.get_profile().flavor, 'crunchy frog')
  1264. class AntiPetRouter(object):
  1265. # A router that only expresses an opinion on syncdb,
  1266. # passing pets to the 'other' database
  1267. def allow_syncdb(self, db, model):
  1268. "Make sure the auth app only appears on the 'other' db"
  1269. if db == 'other':
  1270. return model._meta.object_name == 'Pet'
  1271. else:
  1272. return model._meta.object_name != 'Pet'
  1273. return None
  1274. class FixtureTestCase(TestCase):
  1275. multi_db = True
  1276. fixtures = ['multidb-common', 'multidb']
  1277. def setUp(self):
  1278. # Install the anti-pet router
  1279. self.old_routers = router.routers
  1280. router.routers = [AntiPetRouter()]
  1281. def tearDown(self):
  1282. # Restore the 'other' database as an independent database
  1283. router.routers = self.old_routers
  1284. def test_fixture_loading(self):
  1285. "Multi-db fixtures are loaded correctly"
  1286. # Check that "Pro Django" exists on the default database, but not on other database
  1287. try:
  1288. Book.objects.get(title="Pro Django")
  1289. Book.objects.using('default').get(title="Pro Django")
  1290. except Book.DoesNotExist:
  1291. self.fail('"Pro Django" should exist on default database')
  1292. self.assertRaises(Book.DoesNotExist,
  1293. Book.objects.using('other').get,
  1294. title="Pro Django"
  1295. )
  1296. # Check that "Dive into Python" exists on the default database, but not on other database
  1297. try:
  1298. Book.objects.using('other').get(title="Dive into Python")
  1299. except Book.DoesNotExist:
  1300. self.fail('"Dive into Python" should exist on other database')
  1301. self.assertRaises(Book.DoesNotExist,
  1302. Book.objects.get,
  1303. title="Dive into Python"
  1304. )
  1305. self.assertRaises(Book.DoesNotExist,
  1306. Book.objects.using('default').get,
  1307. title="Dive into Python"
  1308. )
  1309. # Check that "Definitive Guide" exists on the both databases
  1310. try:
  1311. Book.objects.get(title="The Definitive Guide to Django")
  1312. Book.objects.using('default').get(title="The Definitive Guide to Django")
  1313. Book.objects.using('other').get(title="The Definitive Guide to Django")
  1314. except Book.DoesNotExist:
  1315. self.fail('"The Definitive Guide to Django" should exist on both databases')
  1316. def test_pseudo_empty_fixtures(self):
  1317. "A fixture can contain entries, but lead to nothing in the database; this shouldn't raise an error (ref #14068)"
  1318. new_io = StringIO()
  1319. management.call_command('loaddata', 'pets', stdout=new_io, stderr=new_io)
  1320. command_output = new_io.getvalue().strip()
  1321. # No objects will actually be loaded
  1322. self.assertEqual(command_output, "Installed 0 object(s) (of 2) from 1 fixture(s)")
  1323. class PickleQuerySetTestCase(TestCase):
  1324. multi_db = True
  1325. def test_pickling(self):
  1326. for db in connections:
  1327. Book.objects.using(db).create(title='Dive into Python', published=datetime.date(2009, 5, 4))
  1328. qs = Book.objects.all()
  1329. self.assertEqual(qs.db, pickle.loads(pickle.dumps(qs)).db)
  1330. class DatabaseReceiver(object):
  1331. """
  1332. Used in the tests for the database argument in signals (#13552)
  1333. """
  1334. def __call__(self, signal, sender, **kwargs):
  1335. self._database = kwargs['using']
  1336. class WriteToOtherRouter(object):
  1337. """
  1338. A router that sends all writes to the other database.
  1339. """
  1340. def db_for_write(self, model, **hints):
  1341. return "other"
  1342. class SignalTests(TestCase):
  1343. multi_db = True
  1344. def setUp(self):
  1345. self.old_routers = router.routers
  1346. def tearDown(self):
  1347. router.routser = self.old_routers
  1348. def _write_to_other(self):
  1349. "Sends all writes to 'other'."
  1350. router.routers = [WriteToOtherRouter()]
  1351. def _write_to_default(self):
  1352. "Sends all writes to the default DB"
  1353. router.routers = self.old_routers
  1354. def test_database_arg_save_and_delete(self):
  1355. """
  1356. Tests that the pre/post_save signal contains the correct database.
  1357. (#13552)
  1358. """
  1359. # Make some signal receivers
  1360. pre_save_receiver = DatabaseReceiver()
  1361. post_save_receiver = DatabaseReceiver()
  1362. pre_delete_receiver = DatabaseReceiver()
  1363. post_delete_receiver = DatabaseReceiver()
  1364. # Make model and connect receivers
  1365. signals.pre_save.connect(sender=Person, receiver=pre_save_receiver)
  1366. signals.post_save.connect(sender=Person, receiver=post_save_receiver)
  1367. signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
  1368. signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
  1369. p = Person.objects.create(name='Darth Vader')
  1370. # Save and test receivers got calls
  1371. p.save()
  1372. self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
  1373. self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
  1374. # Delete, and test
  1375. p.delete()
  1376. self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
  1377. self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
  1378. # Save again to a different database
  1379. p.save(using="other")
  1380. self.assertEqual(pre_save_receiver._database, "other")
  1381. self.assertEqual(post_save_receiver._database, "other")
  1382. # Delete, and test
  1383. p.delete(using="other")
  1384. self.assertEqual(pre_delete_receiver._database, "other")
  1385. self.assertEqual(post_delete_receiver._database, "other")
  1386. def test_database_arg_m2m(self):
  1387. """
  1388. Test that the m2m_changed signal has a correct database arg (#13552)
  1389. """
  1390. # Make a receiver
  1391. receiver = DatabaseReceiver()
  1392. # Connect it, and make the models
  1393. signals.m2m_changed.connect(receiver=receiver)
  1394. b = Book.objects.create(title="Pro Django",
  1395. published=datetime.date(2008, 12, 16))
  1396. p = Person.objects.create(name="Marty Alchin")
  1397. # Test addition
  1398. b.authors.add(p)
  1399. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1400. self._write_to_other()
  1401. b.authors.add(p)
  1402. self._write_to_default()
  1403. self.assertEqual(receiver._database, "other")
  1404. # Test removal
  1405. b.authors.remove(p)
  1406. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1407. self._write_to_other()
  1408. b.authors.remove(p)
  1409. self._write_to_default()
  1410. self.assertEqual(receiver._database, "other")
  1411. # Test addition in reverse
  1412. p.book_set.add(b)
  1413. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1414. self._write_to_other()
  1415. p.book_set.add(b)
  1416. self._write_to_default()
  1417. self.assertEqual(receiver._database, "other")
  1418. # Test clearing
  1419. b.authors.clear()
  1420. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1421. self._write_to_other()
  1422. b.authors.clear()
  1423. self._write_to_default()
  1424. self.assertEqual(receiver._database, "other")
  1425. class AttributeErrorRouter(object):
  1426. "A router to test the exception handling of ConnectionRouter"
  1427. def db_for_read(self, model, **hints):
  1428. raise AttributeError
  1429. def db_for_write(self, model, **hints):
  1430. raise AttributeError
  1431. class RouterAttributeErrorTestCase(TestCase):
  1432. multi_db = True
  1433. def setUp(self):
  1434. self.old_routers = router.routers
  1435. router.routers = [AttributeErrorRouter()]
  1436. def tearDown(self):
  1437. router.routers = self.old_routers
  1438. def test_attribute_error_read(self):
  1439. "Check that the AttributeError from AttributeErrorRouter bubbles up"
  1440. router.routers = [] # Reset routers so we can save a Book instance
  1441. b = Book.objects.create(title="Pro Django",
  1442. published=datetime.date(2008, 12, 16))
  1443. router.routers = [AttributeErrorRouter()] # Install our router
  1444. self.assertRaises(AttributeError, Book.objects.get, pk=b.pk)
  1445. def test_attribute_error_save(self):
  1446. "Check that the AttributeError from AttributeErrorRouter bubbles up"
  1447. dive = Book()
  1448. dive.title="Dive into Python"
  1449. dive.published = datetime.date(2009, 5, 4)
  1450. self.assertRaises(AttributeError, dive.save)
  1451. def test_attribute_error_delete(self):
  1452. "Check that the AttributeError from AttributeErrorRouter bubbles up"
  1453. router.routers = [] # Reset routers so we can save our Book, Person instances
  1454. b = Book.objects.create(title="Pro Django",
  1455. published=datetime.date(2008, 12, 16))
  1456. p = Person.objects.create(name="Marty Alchin")
  1457. b.authors = [p]
  1458. b.editor = p
  1459. router.routers = [AttributeErrorRouter()] # Install our router
  1460. self.assertRaises(AttributeError, b.delete)
  1461. def test_attribute_error_m2m(self):
  1462. "Check that the AttributeError from AttributeErrorRouter bubbles up"
  1463. router.routers = [] # Reset routers so we can save our Book, Person instances
  1464. b = Book.objects.create(title="Pro Django",
  1465. published=datetime.date(2008, 12, 16))
  1466. p = Person.objects.create(name="Marty Alchin")
  1467. router.routers = [AttributeErrorRouter()] # Install our router
  1468. self.assertRaises(AttributeError, setattr, b, 'authors', [p])
  1469. class ModelMetaRouter(object):
  1470. "A router to ensure model arguments are real model classes"
  1471. def db_for_write(self, model, **hints):
  1472. if not hasattr(model, '_meta'):
  1473. raise ValueError
  1474. class RouterModelArgumentTestCase(TestCase):
  1475. multi_db = True
  1476. def setUp(self):
  1477. self.old_routers = router.routers
  1478. router.routers = [ModelMetaRouter()]
  1479. def tearDown(self):
  1480. router.routers = self.old_routers
  1481. def test_m2m_collection(self):
  1482. b = Book.objects.create(title="Pro Django",
  1483. published=datetime.date(2008, 12, 16))
  1484. p = Person.objects.create(name="Marty Alchin")
  1485. # test add
  1486. b.authors.add(p)
  1487. # test remove
  1488. b.authors.remove(p)
  1489. # test clear
  1490. b.authors.clear()
  1491. # test setattr
  1492. b.authors = [p]
  1493. # test M2M collection
  1494. b.delete()
  1495. def test_foreignkey_collection(self):
  1496. person = Person.objects.create(name='Bob')
  1497. pet = Pet.objects.create(owner=person, name='Wart')
  1498. # test related FK collection
  1499. person.delete()