tests.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177
  1. from __future__ import unicode_literals
  2. import datetime
  3. import pickle
  4. from operator import attrgetter
  5. from django.contrib.auth.models import User
  6. from django.contrib.contenttypes.models import ContentType
  7. from django.core import management
  8. from django.db import DEFAULT_DB_ALIAS, connections, router, transaction
  9. from django.db.models import signals
  10. from django.db.utils import ConnectionRouter
  11. from django.test import SimpleTestCase, TestCase, override_settings
  12. from django.utils.six import StringIO
  13. from .models import Book, Person, Pet, Review, UserProfile
  14. from .routers import AuthRouter, TestRouter, WriteRouter
  15. class QueryTestCase(TestCase):
  16. multi_db = True
  17. def test_db_selection(self):
  18. "Check that querysets will use the default database by default"
  19. self.assertEqual(Book.objects.db, DEFAULT_DB_ALIAS)
  20. self.assertEqual(Book.objects.all().db, DEFAULT_DB_ALIAS)
  21. self.assertEqual(Book.objects.using('other').db, 'other')
  22. self.assertEqual(Book.objects.db_manager('other').db, 'other')
  23. self.assertEqual(Book.objects.db_manager('other').all().db, 'other')
  24. def test_default_creation(self):
  25. "Objects created on the default database don't leak onto other databases"
  26. # Create a book on the default database using create()
  27. Book.objects.create(title="Pro Django",
  28. published=datetime.date(2008, 12, 16))
  29. # Create a book on the default database using a save
  30. dive = Book()
  31. dive.title = "Dive into Python"
  32. dive.published = datetime.date(2009, 5, 4)
  33. dive.save()
  34. # Check that book exists on the default database, but not on other database
  35. try:
  36. Book.objects.get(title="Pro Django")
  37. Book.objects.using('default').get(title="Pro Django")
  38. except Book.DoesNotExist:
  39. self.fail('"Pro Django" should exist on default database')
  40. self.assertRaises(
  41. Book.DoesNotExist,
  42. Book.objects.using('other').get,
  43. title="Pro Django"
  44. )
  45. try:
  46. Book.objects.get(title="Dive into Python")
  47. Book.objects.using('default').get(title="Dive into Python")
  48. except Book.DoesNotExist:
  49. self.fail('"Dive into Python" should exist on default database')
  50. self.assertRaises(
  51. Book.DoesNotExist,
  52. Book.objects.using('other').get,
  53. title="Dive into Python"
  54. )
  55. def test_other_creation(self):
  56. "Objects created on another database don't leak onto the default database"
  57. # Create a book on the second database
  58. Book.objects.using('other').create(title="Pro Django",
  59. published=datetime.date(2008, 12, 16))
  60. # Create a book on the default database using a save
  61. dive = Book()
  62. dive.title = "Dive into Python"
  63. dive.published = datetime.date(2009, 5, 4)
  64. dive.save(using='other')
  65. # Check that book exists on the default database, but not on other database
  66. try:
  67. Book.objects.using('other').get(title="Pro Django")
  68. except Book.DoesNotExist:
  69. self.fail('"Pro Django" should exist on other database')
  70. self.assertRaises(
  71. Book.DoesNotExist,
  72. Book.objects.get,
  73. title="Pro Django"
  74. )
  75. self.assertRaises(
  76. 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(
  85. Book.DoesNotExist,
  86. Book.objects.get,
  87. title="Dive into Python"
  88. )
  89. self.assertRaises(
  90. Book.DoesNotExist,
  91. Book.objects.using('default').get,
  92. title="Dive into Python"
  93. )
  94. def test_refresh(self):
  95. dive = Book()
  96. dive.title = "Dive into Python"
  97. dive = Book()
  98. dive.title = "Dive into Python"
  99. dive.published = datetime.date(2009, 5, 4)
  100. dive.save(using='other')
  101. dive.published = datetime.date(2009, 5, 4)
  102. dive.save(using='other')
  103. dive2 = Book.objects.using('other').get()
  104. dive2.title = "Dive into Python (on default)"
  105. dive2.save(using='default')
  106. dive.refresh_from_db()
  107. self.assertEqual(dive.title, "Dive into Python")
  108. dive.refresh_from_db(using='default')
  109. self.assertEqual(dive.title, "Dive into Python (on default)")
  110. self.assertEqual(dive._state.db, "default")
  111. def test_basic_queries(self):
  112. "Queries are constrained to a single database"
  113. dive = Book.objects.using('other').create(title="Dive into Python",
  114. published=datetime.date(2009, 5, 4))
  115. dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4))
  116. self.assertEqual(dive.title, "Dive into Python")
  117. self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, published=datetime.date(2009, 5, 4))
  118. dive = Book.objects.using('other').get(title__icontains="dive")
  119. self.assertEqual(dive.title, "Dive into Python")
  120. self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title__icontains="dive")
  121. dive = Book.objects.using('other').get(title__iexact="dive INTO python")
  122. self.assertEqual(dive.title, "Dive into Python")
  123. self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title__iexact="dive INTO python")
  124. dive = Book.objects.using('other').get(published__year=2009)
  125. self.assertEqual(dive.title, "Dive into Python")
  126. self.assertEqual(dive.published, datetime.date(2009, 5, 4))
  127. self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, published__year=2009)
  128. years = Book.objects.using('other').dates('published', 'year')
  129. self.assertEqual([o.year for o in years], [2009])
  130. years = Book.objects.using('default').dates('published', 'year')
  131. self.assertEqual([o.year for o in years], [])
  132. months = Book.objects.using('other').dates('published', 'month')
  133. self.assertEqual([o.month for o in months], [5])
  134. months = Book.objects.using('default').dates('published', 'month')
  135. self.assertEqual([o.month for o in months], [])
  136. def test_m2m_separation(self):
  137. "M2M fields are constrained to a single database"
  138. # Create a book and author on the default database
  139. pro = Book.objects.create(title="Pro Django",
  140. published=datetime.date(2008, 12, 16))
  141. marty = Person.objects.create(name="Marty Alchin")
  142. # Create a book and author on the other database
  143. dive = Book.objects.using('other').create(title="Dive into Python",
  144. published=datetime.date(2009, 5, 4))
  145. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  146. # Save the author relations
  147. pro.authors.set([marty])
  148. dive.authors.set([mark])
  149. # Inspect the m2m tables directly.
  150. # There should be 1 entry in each database
  151. self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
  152. self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
  153. # Check that queries work across m2m joins
  154. self.assertEqual(
  155. list(Book.objects.using('default').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
  156. ['Pro Django']
  157. )
  158. self.assertEqual(
  159. list(Book.objects.using('other').filter(authors__name='Marty Alchin').values_list('title', flat=True)),
  160. []
  161. )
  162. self.assertEqual(
  163. list(Book.objects.using('default').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  164. []
  165. )
  166. self.assertEqual(
  167. list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  168. ['Dive into Python']
  169. )
  170. # Reget the objects to clear caches
  171. dive = Book.objects.using('other').get(title="Dive into Python")
  172. mark = Person.objects.using('other').get(name="Mark Pilgrim")
  173. # Retrieve related object by descriptor. Related objects should be database-bound
  174. self.assertEqual(list(dive.authors.all().values_list('name', flat=True)),
  175. ['Mark Pilgrim'])
  176. self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)),
  177. ['Dive into Python'])
  178. def test_m2m_forward_operations(self):
  179. "M2M forward manipulations are all constrained to a single DB"
  180. # Create a book and author on the other database
  181. dive = Book.objects.using('other').create(title="Dive into Python",
  182. published=datetime.date(2009, 5, 4))
  183. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  184. # Save the author relations
  185. dive.authors.set([mark])
  186. # Add a second author
  187. john = Person.objects.using('other').create(name="John Smith")
  188. self.assertEqual(
  189. list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
  190. []
  191. )
  192. dive.authors.add(john)
  193. self.assertEqual(
  194. list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  195. ['Dive into Python']
  196. )
  197. self.assertEqual(
  198. list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
  199. ['Dive into Python']
  200. )
  201. # Remove the second author
  202. dive.authors.remove(john)
  203. self.assertEqual(
  204. list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  205. ['Dive into Python']
  206. )
  207. self.assertEqual(
  208. list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
  209. []
  210. )
  211. # Clear all authors
  212. dive.authors.clear()
  213. self.assertEqual(
  214. list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  215. []
  216. )
  217. self.assertEqual(
  218. list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)),
  219. []
  220. )
  221. # Create an author through the m2m interface
  222. dive.authors.create(name='Jane Brown')
  223. self.assertEqual(
  224. list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)),
  225. []
  226. )
  227. self.assertEqual(
  228. list(Book.objects.using('other').filter(authors__name='Jane Brown').values_list('title', flat=True)),
  229. ['Dive into Python']
  230. )
  231. def test_m2m_reverse_operations(self):
  232. "M2M reverse manipulations are all constrained to a single DB"
  233. # Create a book and author on the other database
  234. dive = Book.objects.using('other').create(title="Dive into Python",
  235. published=datetime.date(2009, 5, 4))
  236. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  237. # Save the author relations
  238. dive.authors.set([mark])
  239. # Create a second book on the other database
  240. grease = Book.objects.using('other').create(title="Greasemonkey Hacks",
  241. published=datetime.date(2005, 11, 1))
  242. # Add a books to the m2m
  243. mark.book_set.add(grease)
  244. self.assertEqual(
  245. list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
  246. ['Mark Pilgrim']
  247. )
  248. self.assertEqual(
  249. list(
  250. Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)
  251. ),
  252. ['Mark Pilgrim']
  253. )
  254. # Remove a book from the m2m
  255. mark.book_set.remove(grease)
  256. self.assertEqual(
  257. list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
  258. ['Mark Pilgrim']
  259. )
  260. self.assertEqual(
  261. list(
  262. Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)
  263. ),
  264. []
  265. )
  266. # Clear the books associated with mark
  267. mark.book_set.clear()
  268. self.assertEqual(
  269. list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
  270. []
  271. )
  272. self.assertEqual(
  273. list(
  274. Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)
  275. ),
  276. []
  277. )
  278. # Create a book through the m2m interface
  279. mark.book_set.create(title="Dive into HTML5", published=datetime.date(2020, 1, 1))
  280. self.assertEqual(
  281. list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)),
  282. []
  283. )
  284. self.assertEqual(
  285. list(Person.objects.using('other').filter(book__title='Dive into HTML5').values_list('name', flat=True)),
  286. ['Mark Pilgrim']
  287. )
  288. def test_m2m_cross_database_protection(self):
  289. "Operations that involve sharing M2M objects across databases raise an error"
  290. # Create a book and author on the default database
  291. pro = Book.objects.create(title="Pro Django",
  292. published=datetime.date(2008, 12, 16))
  293. marty = Person.objects.create(name="Marty Alchin")
  294. # Create a book and author on the other database
  295. dive = Book.objects.using('other').create(title="Dive into Python",
  296. published=datetime.date(2009, 5, 4))
  297. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  298. # Set a foreign key set with an object from a different database
  299. with self.assertRaises(ValueError):
  300. with transaction.atomic(using='default'):
  301. marty.edited.set([pro, dive])
  302. # Add to an m2m with an object from a different database
  303. with self.assertRaises(ValueError):
  304. with transaction.atomic(using='default'):
  305. marty.book_set.add(dive)
  306. # Set a m2m with an object from a different database
  307. with self.assertRaises(ValueError):
  308. with transaction.atomic(using='default'):
  309. marty.book_set.set([pro, dive])
  310. # Add to a reverse m2m with an object from a different database
  311. with self.assertRaises(ValueError):
  312. with transaction.atomic(using='other'):
  313. dive.authors.add(marty)
  314. # Set a reverse m2m with an object from a different database
  315. with self.assertRaises(ValueError):
  316. with transaction.atomic(using='other'):
  317. dive.authors.set([mark, marty])
  318. def test_m2m_deletion(self):
  319. "Cascaded deletions of m2m relations issue queries on the right database"
  320. # Create a book and author on the other database
  321. dive = Book.objects.using('other').create(title="Dive into Python",
  322. published=datetime.date(2009, 5, 4))
  323. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  324. dive.authors.set([mark])
  325. # Check the initial state
  326. self.assertEqual(Person.objects.using('default').count(), 0)
  327. self.assertEqual(Book.objects.using('default').count(), 0)
  328. self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
  329. self.assertEqual(Person.objects.using('other').count(), 1)
  330. self.assertEqual(Book.objects.using('other').count(), 1)
  331. self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
  332. # Delete the object on the other database
  333. dive.delete(using='other')
  334. self.assertEqual(Person.objects.using('default').count(), 0)
  335. self.assertEqual(Book.objects.using('default').count(), 0)
  336. self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
  337. # The person still exists ...
  338. self.assertEqual(Person.objects.using('other').count(), 1)
  339. # ... but the book has been deleted
  340. self.assertEqual(Book.objects.using('other').count(), 0)
  341. # ... and the relationship object has also been deleted.
  342. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  343. # Now try deletion in the reverse direction. Set up the relation again
  344. dive = Book.objects.using('other').create(title="Dive into Python",
  345. published=datetime.date(2009, 5, 4))
  346. dive.authors.set([mark])
  347. # Check the initial state
  348. self.assertEqual(Person.objects.using('default').count(), 0)
  349. self.assertEqual(Book.objects.using('default').count(), 0)
  350. self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
  351. self.assertEqual(Person.objects.using('other').count(), 1)
  352. self.assertEqual(Book.objects.using('other').count(), 1)
  353. self.assertEqual(Book.authors.through.objects.using('other').count(), 1)
  354. # Delete the object on the other database
  355. mark.delete(using='other')
  356. self.assertEqual(Person.objects.using('default').count(), 0)
  357. self.assertEqual(Book.objects.using('default').count(), 0)
  358. self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
  359. # The person has been deleted ...
  360. self.assertEqual(Person.objects.using('other').count(), 0)
  361. # ... but the book still exists
  362. self.assertEqual(Book.objects.using('other').count(), 1)
  363. # ... and the relationship object has been deleted.
  364. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  365. def test_foreign_key_separation(self):
  366. "FK fields are constrained to a single database"
  367. # Create a book and author on the default database
  368. pro = Book.objects.create(title="Pro Django",
  369. published=datetime.date(2008, 12, 16))
  370. george = Person.objects.create(name="George Vilches")
  371. # Create a book and author on the other database
  372. dive = Book.objects.using('other').create(title="Dive into Python",
  373. published=datetime.date(2009, 5, 4))
  374. chris = Person.objects.using('other').create(name="Chris Mills")
  375. # Save the author's favorite books
  376. pro.editor = george
  377. pro.save()
  378. dive.editor = chris
  379. dive.save()
  380. pro = Book.objects.using('default').get(title="Pro Django")
  381. self.assertEqual(pro.editor.name, "George Vilches")
  382. dive = Book.objects.using('other').get(title="Dive into Python")
  383. self.assertEqual(dive.editor.name, "Chris Mills")
  384. # Check that queries work across foreign key joins
  385. self.assertEqual(
  386. list(Person.objects.using('default').filter(edited__title='Pro Django').values_list('name', flat=True)),
  387. ['George Vilches']
  388. )
  389. self.assertEqual(
  390. list(Person.objects.using('other').filter(edited__title='Pro Django').values_list('name', flat=True)),
  391. []
  392. )
  393. self.assertEqual(
  394. list(
  395. Person.objects.using('default').filter(edited__title='Dive into Python').values_list('name', flat=True)
  396. ),
  397. []
  398. )
  399. self.assertEqual(
  400. list(
  401. Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
  402. ),
  403. ['Chris Mills']
  404. )
  405. # Reget the objects to clear caches
  406. chris = Person.objects.using('other').get(name="Chris Mills")
  407. dive = Book.objects.using('other').get(title="Dive into Python")
  408. # Retrieve related object by descriptor. Related objects should be database-bound
  409. self.assertEqual(list(chris.edited.values_list('title', flat=True)),
  410. ['Dive into Python'])
  411. def test_foreign_key_reverse_operations(self):
  412. "FK reverse manipulations are all constrained to a single DB"
  413. dive = Book.objects.using('other').create(title="Dive into Python",
  414. published=datetime.date(2009, 5, 4))
  415. chris = Person.objects.using('other').create(name="Chris Mills")
  416. # Save the author relations
  417. dive.editor = chris
  418. dive.save()
  419. # Add a second book edited by chris
  420. html5 = Book.objects.using('other').create(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
  421. self.assertEqual(
  422. list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
  423. []
  424. )
  425. chris.edited.add(html5)
  426. self.assertEqual(
  427. list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
  428. ['Chris Mills']
  429. )
  430. self.assertEqual(
  431. list(
  432. Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
  433. ),
  434. ['Chris Mills']
  435. )
  436. # Remove the second editor
  437. chris.edited.remove(html5)
  438. self.assertEqual(
  439. list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
  440. []
  441. )
  442. self.assertEqual(
  443. list(
  444. Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
  445. ),
  446. ['Chris Mills']
  447. )
  448. # Clear all edited books
  449. chris.edited.clear()
  450. self.assertEqual(
  451. list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
  452. []
  453. )
  454. self.assertEqual(
  455. list(
  456. Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
  457. ),
  458. []
  459. )
  460. # Create an author through the m2m interface
  461. chris.edited.create(title='Dive into Water', published=datetime.date(2010, 3, 15))
  462. self.assertEqual(
  463. list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)),
  464. []
  465. )
  466. self.assertEqual(
  467. list(Person.objects.using('other').filter(edited__title='Dive into Water').values_list('name', flat=True)),
  468. ['Chris Mills']
  469. )
  470. self.assertEqual(
  471. list(
  472. Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)
  473. ),
  474. []
  475. )
  476. def test_foreign_key_cross_database_protection(self):
  477. "Operations that involve sharing FK objects across databases raise an error"
  478. # Create a book and author on the default database
  479. pro = Book.objects.create(title="Pro Django",
  480. published=datetime.date(2008, 12, 16))
  481. marty = Person.objects.create(name="Marty Alchin")
  482. # Create a book and author on the other database
  483. dive = Book.objects.using('other').create(title="Dive into Python",
  484. published=datetime.date(2009, 5, 4))
  485. # Set a foreign key with an object from a different database
  486. with self.assertRaises(ValueError):
  487. dive.editor = marty
  488. # Set a foreign key set with an object from a different database
  489. with self.assertRaises(ValueError):
  490. with transaction.atomic(using='default'):
  491. marty.edited.set([pro, dive])
  492. # Add to a foreign key set with an object from a different database
  493. with self.assertRaises(ValueError):
  494. with transaction.atomic(using='default'):
  495. marty.edited.add(dive)
  496. def test_foreign_key_deletion(self):
  497. "Cascaded deletions of Foreign Key relations issue queries on the right database"
  498. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  499. Pet.objects.using('other').create(name="Fido", owner=mark)
  500. # Check the initial state
  501. self.assertEqual(Person.objects.using('default').count(), 0)
  502. self.assertEqual(Pet.objects.using('default').count(), 0)
  503. self.assertEqual(Person.objects.using('other').count(), 1)
  504. self.assertEqual(Pet.objects.using('other').count(), 1)
  505. # Delete the person object, which will cascade onto the pet
  506. mark.delete(using='other')
  507. self.assertEqual(Person.objects.using('default').count(), 0)
  508. self.assertEqual(Pet.objects.using('default').count(), 0)
  509. # Both the pet and the person have been deleted from the right database
  510. self.assertEqual(Person.objects.using('other').count(), 0)
  511. self.assertEqual(Pet.objects.using('other').count(), 0)
  512. def test_foreign_key_validation(self):
  513. "ForeignKey.validate() uses the correct database"
  514. mickey = Person.objects.using('other').create(name="Mickey")
  515. pluto = Pet.objects.using('other').create(name="Pluto", owner=mickey)
  516. self.assertIsNone(pluto.full_clean())
  517. def test_o2o_separation(self):
  518. "OneToOne fields are constrained to a single database"
  519. # Create a user and profile on the default database
  520. alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com')
  521. alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate')
  522. # Create a user and profile on the other database
  523. bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com')
  524. bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog')
  525. # Retrieve related objects; queries should be database constrained
  526. alice = User.objects.using('default').get(username="alice")
  527. self.assertEqual(alice.userprofile.flavor, "chocolate")
  528. bob = User.objects.using('other').get(username="bob")
  529. self.assertEqual(bob.userprofile.flavor, "crunchy frog")
  530. # Check that queries work across joins
  531. self.assertEqual(
  532. list(
  533. User.objects.using('default')
  534. .filter(userprofile__flavor='chocolate').values_list('username', flat=True)
  535. ),
  536. ['alice']
  537. )
  538. self.assertEqual(
  539. list(
  540. User.objects.using('other')
  541. .filter(userprofile__flavor='chocolate').values_list('username', flat=True)
  542. ),
  543. []
  544. )
  545. self.assertEqual(
  546. list(
  547. User.objects.using('default')
  548. .filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)
  549. ),
  550. []
  551. )
  552. self.assertEqual(
  553. list(
  554. User.objects.using('other')
  555. .filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)
  556. ),
  557. ['bob']
  558. )
  559. # Reget the objects to clear caches
  560. alice_profile = UserProfile.objects.using('default').get(flavor='chocolate')
  561. bob_profile = UserProfile.objects.using('other').get(flavor='crunchy frog')
  562. # Retrieve related object by descriptor. Related objects should be database-bound
  563. self.assertEqual(alice_profile.user.username, 'alice')
  564. self.assertEqual(bob_profile.user.username, 'bob')
  565. def test_o2o_cross_database_protection(self):
  566. "Operations that involve sharing FK objects across databases raise an error"
  567. # Create a user and profile on the default database
  568. alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com')
  569. # Create a user and profile on the other database
  570. bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com')
  571. # Set a one-to-one relation with an object from a different database
  572. alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate')
  573. with self.assertRaises(ValueError):
  574. bob.userprofile = alice_profile
  575. # BUT! if you assign a FK object when the base object hasn't
  576. # been saved yet, you implicitly assign the database for the
  577. # base object.
  578. bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog')
  579. new_bob_profile = UserProfile(flavor="spring surprise")
  580. # assigning a profile requires an explicit pk as the object isn't saved
  581. charlie = User(pk=51, username='charlie', email='charlie@example.com')
  582. charlie.set_unusable_password()
  583. # initially, no db assigned
  584. self.assertEqual(new_bob_profile._state.db, None)
  585. self.assertEqual(charlie._state.db, None)
  586. # old object comes from 'other', so the new object is set to use 'other'...
  587. new_bob_profile.user = bob
  588. charlie.userprofile = bob_profile
  589. self.assertEqual(new_bob_profile._state.db, 'other')
  590. self.assertEqual(charlie._state.db, 'other')
  591. # ... but it isn't saved yet
  592. self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)),
  593. ['bob'])
  594. self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
  595. ['crunchy frog'])
  596. # When saved (no using required), new objects goes to 'other'
  597. charlie.save()
  598. bob_profile.save()
  599. new_bob_profile.save()
  600. self.assertEqual(list(User.objects.using('default').values_list('username', flat=True)),
  601. ['alice'])
  602. self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)),
  603. ['bob', 'charlie'])
  604. self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)),
  605. ['chocolate'])
  606. self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
  607. ['crunchy frog', 'spring surprise'])
  608. # This also works if you assign the O2O relation in the constructor
  609. denise = User.objects.db_manager('other').create_user('denise', 'denise@example.com')
  610. denise_profile = UserProfile(flavor="tofu", user=denise)
  611. self.assertEqual(denise_profile._state.db, 'other')
  612. # ... but it isn't saved yet
  613. self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)),
  614. ['chocolate'])
  615. self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
  616. ['crunchy frog', 'spring surprise'])
  617. # When saved, the new profile goes to 'other'
  618. denise_profile.save()
  619. self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)),
  620. ['chocolate'])
  621. self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
  622. ['crunchy frog', 'spring surprise', 'tofu'])
  623. def test_generic_key_separation(self):
  624. "Generic fields are constrained to a single database"
  625. # Create a book and author on the default database
  626. pro = Book.objects.create(title="Pro Django",
  627. published=datetime.date(2008, 12, 16))
  628. review1 = Review.objects.create(source="Python Monthly", content_object=pro)
  629. # Create a book and author on the other database
  630. dive = Book.objects.using('other').create(title="Dive into Python",
  631. published=datetime.date(2009, 5, 4))
  632. review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
  633. review1 = Review.objects.using('default').get(source="Python Monthly")
  634. self.assertEqual(review1.content_object.title, "Pro Django")
  635. review2 = Review.objects.using('other').get(source="Python Weekly")
  636. self.assertEqual(review2.content_object.title, "Dive into Python")
  637. # Reget the objects to clear caches
  638. dive = Book.objects.using('other').get(title="Dive into Python")
  639. # Retrieve related object by descriptor. Related objects should be database-bound
  640. self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)),
  641. ['Python Weekly'])
  642. def test_generic_key_reverse_operations(self):
  643. "Generic reverse manipulations are all constrained to a single DB"
  644. dive = Book.objects.using('other').create(title="Dive into Python",
  645. published=datetime.date(2009, 5, 4))
  646. temp = Book.objects.using('other').create(title="Temp",
  647. published=datetime.date(2009, 5, 4))
  648. review1 = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
  649. review2 = Review.objects.using('other').create(source="Python Monthly", content_object=temp)
  650. self.assertEqual(
  651. list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
  652. []
  653. )
  654. self.assertEqual(
  655. list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  656. ['Python Weekly']
  657. )
  658. # Add a second review
  659. dive.reviews.add(review2)
  660. self.assertEqual(
  661. list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
  662. []
  663. )
  664. self.assertEqual(
  665. list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  666. ['Python Monthly', 'Python Weekly']
  667. )
  668. # Remove the second author
  669. dive.reviews.remove(review1)
  670. self.assertEqual(
  671. list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
  672. []
  673. )
  674. self.assertEqual(
  675. list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  676. ['Python Monthly']
  677. )
  678. # Clear all reviews
  679. dive.reviews.clear()
  680. self.assertEqual(
  681. list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
  682. []
  683. )
  684. self.assertEqual(
  685. list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  686. []
  687. )
  688. # Create an author through the generic interface
  689. dive.reviews.create(source='Python Daily')
  690. self.assertEqual(
  691. list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)),
  692. []
  693. )
  694. self.assertEqual(
  695. list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  696. ['Python Daily']
  697. )
  698. def test_generic_key_cross_database_protection(self):
  699. "Operations that involve sharing generic key objects across databases raise an error"
  700. # Create a book and author on the default database
  701. pro = Book.objects.create(title="Pro Django",
  702. published=datetime.date(2008, 12, 16))
  703. review1 = Review.objects.create(source="Python Monthly", content_object=pro)
  704. # Create a book and author on the other database
  705. dive = Book.objects.using('other').create(title="Dive into Python",
  706. published=datetime.date(2009, 5, 4))
  707. Review.objects.using('other').create(source="Python Weekly", content_object=dive)
  708. # Set a foreign key with an object from a different database
  709. with self.assertRaises(ValueError):
  710. review1.content_object = dive
  711. # Add to a foreign key set with an object from a different database
  712. with self.assertRaises(ValueError):
  713. with transaction.atomic(using='other'):
  714. dive.reviews.add(review1)
  715. # BUT! if you assign a FK object when the base object hasn't
  716. # been saved yet, you implicitly assign the database for the
  717. # base object.
  718. review3 = Review(source="Python Daily")
  719. # initially, no db assigned
  720. self.assertEqual(review3._state.db, None)
  721. # Dive comes from 'other', so review3 is set to use 'other'...
  722. review3.content_object = dive
  723. self.assertEqual(review3._state.db, 'other')
  724. # ... but it isn't saved yet
  725. self.assertEqual(
  726. list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
  727. ['Python Monthly']
  728. )
  729. self.assertEqual(
  730. list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  731. ['Python Weekly']
  732. )
  733. # When saved, John goes to 'other'
  734. review3.save()
  735. self.assertEqual(
  736. list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
  737. ['Python Monthly']
  738. )
  739. self.assertEqual(
  740. list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
  741. ['Python Daily', 'Python Weekly']
  742. )
  743. def test_generic_key_deletion(self):
  744. "Cascaded deletions of Generic Key relations issue queries on the right database"
  745. dive = Book.objects.using('other').create(title="Dive into Python",
  746. published=datetime.date(2009, 5, 4))
  747. Review.objects.using('other').create(source="Python Weekly", content_object=dive)
  748. # Check the initial state
  749. self.assertEqual(Book.objects.using('default').count(), 0)
  750. self.assertEqual(Review.objects.using('default').count(), 0)
  751. self.assertEqual(Book.objects.using('other').count(), 1)
  752. self.assertEqual(Review.objects.using('other').count(), 1)
  753. # Delete the Book object, which will cascade onto the pet
  754. dive.delete(using='other')
  755. self.assertEqual(Book.objects.using('default').count(), 0)
  756. self.assertEqual(Review.objects.using('default').count(), 0)
  757. # Both the pet and the person have been deleted from the right database
  758. self.assertEqual(Book.objects.using('other').count(), 0)
  759. self.assertEqual(Review.objects.using('other').count(), 0)
  760. def test_ordering(self):
  761. "get_next_by_XXX commands stick to a single database"
  762. Book.objects.create(title="Pro Django",
  763. published=datetime.date(2008, 12, 16))
  764. dive = Book.objects.using('other').create(title="Dive into Python",
  765. published=datetime.date(2009, 5, 4))
  766. learn = Book.objects.using('other').create(title="Learning Python",
  767. published=datetime.date(2008, 7, 16))
  768. self.assertEqual(learn.get_next_by_published().title, "Dive into Python")
  769. self.assertEqual(dive.get_previous_by_published().title, "Learning Python")
  770. def test_raw(self):
  771. "test the raw() method across databases"
  772. dive = Book.objects.using('other').create(title="Dive into Python",
  773. published=datetime.date(2009, 5, 4))
  774. val = Book.objects.db_manager("other").raw('SELECT id FROM multiple_database_book')
  775. self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk"))
  776. val = Book.objects.raw('SELECT id FROM multiple_database_book').using('other')
  777. self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk"))
  778. def test_select_related(self):
  779. "Database assignment is retained if an object is retrieved with select_related()"
  780. # Create a book and author on the other database
  781. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  782. Book.objects.using('other').create(title="Dive into Python",
  783. published=datetime.date(2009, 5, 4),
  784. editor=mark)
  785. # Retrieve the Person using select_related()
  786. book = Book.objects.using('other').select_related('editor').get(title="Dive into Python")
  787. # The editor instance should have a db state
  788. self.assertEqual(book.editor._state.db, 'other')
  789. def test_subquery(self):
  790. """Make sure as_sql works with subqueries and primary/replica."""
  791. sub = Person.objects.using('other').filter(name='fff')
  792. qs = Book.objects.filter(editor__in=sub)
  793. # When you call __str__ on the query object, it doesn't know about using
  794. # so it falls back to the default. If the subquery explicitly uses a
  795. # different database, an error should be raised.
  796. self.assertRaises(ValueError, str, qs.query)
  797. # Evaluating the query shouldn't work, either
  798. with self.assertRaises(ValueError):
  799. for obj in qs:
  800. pass
  801. def test_related_manager(self):
  802. "Related managers return managers, not querysets"
  803. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  804. # extra_arg is removed by the BookManager's implementation of
  805. # create(); but the BookManager's implementation won't get called
  806. # unless edited returns a Manager, not a queryset
  807. mark.book_set.create(title="Dive into Python",
  808. published=datetime.date(2009, 5, 4),
  809. extra_arg=True)
  810. mark.book_set.get_or_create(title="Dive into Python",
  811. published=datetime.date(2009, 5, 4),
  812. extra_arg=True)
  813. mark.edited.create(title="Dive into Water",
  814. published=datetime.date(2009, 5, 4),
  815. extra_arg=True)
  816. mark.edited.get_or_create(title="Dive into Water",
  817. published=datetime.date(2009, 5, 4),
  818. extra_arg=True)
  819. class ConnectionRouterTestCase(SimpleTestCase):
  820. @override_settings(DATABASE_ROUTERS=[
  821. 'multiple_database.tests.TestRouter',
  822. 'multiple_database.tests.WriteRouter'])
  823. def test_router_init_default(self):
  824. connection_router = ConnectionRouter()
  825. self.assertListEqual([r.__class__.__name__ for r in connection_router.routers],
  826. ['TestRouter', 'WriteRouter'])
  827. def test_router_init_arg(self):
  828. connection_router = ConnectionRouter([
  829. 'multiple_database.tests.TestRouter',
  830. 'multiple_database.tests.WriteRouter'
  831. ])
  832. self.assertListEqual([r.__class__.__name__ for r in connection_router.routers],
  833. ['TestRouter', 'WriteRouter'])
  834. # Init with instances instead of strings
  835. connection_router = ConnectionRouter([TestRouter(), WriteRouter()])
  836. self.assertListEqual([r.__class__.__name__ for r in connection_router.routers],
  837. ['TestRouter', 'WriteRouter'])
  838. # Make the 'other' database appear to be a replica of the 'default'
  839. @override_settings(DATABASE_ROUTERS=[TestRouter()])
  840. class RouterTestCase(TestCase):
  841. multi_db = True
  842. def test_db_selection(self):
  843. "Check that querysets obey the router for db suggestions"
  844. self.assertEqual(Book.objects.db, 'other')
  845. self.assertEqual(Book.objects.all().db, 'other')
  846. self.assertEqual(Book.objects.using('default').db, 'default')
  847. self.assertEqual(Book.objects.db_manager('default').db, 'default')
  848. self.assertEqual(Book.objects.db_manager('default').all().db, 'default')
  849. def test_migrate_selection(self):
  850. "Synchronization behavior is predictable"
  851. self.assertTrue(router.allow_migrate_model('default', User))
  852. self.assertTrue(router.allow_migrate_model('default', Book))
  853. self.assertTrue(router.allow_migrate_model('other', User))
  854. self.assertTrue(router.allow_migrate_model('other', Book))
  855. with override_settings(DATABASE_ROUTERS=[TestRouter(), AuthRouter()]):
  856. # Add the auth router to the chain. TestRouter is a universal
  857. # synchronizer, so it should have no effect.
  858. self.assertTrue(router.allow_migrate_model('default', User))
  859. self.assertTrue(router.allow_migrate_model('default', Book))
  860. self.assertTrue(router.allow_migrate_model('other', User))
  861. self.assertTrue(router.allow_migrate_model('other', Book))
  862. with override_settings(DATABASE_ROUTERS=[AuthRouter(), TestRouter()]):
  863. # Now check what happens if the router order is reversed.
  864. self.assertFalse(router.allow_migrate_model('default', User))
  865. self.assertTrue(router.allow_migrate_model('default', Book))
  866. self.assertTrue(router.allow_migrate_model('other', User))
  867. self.assertTrue(router.allow_migrate_model('other', Book))
  868. def test_partial_router(self):
  869. "A router can choose to implement a subset of methods"
  870. dive = Book.objects.using('other').create(title="Dive into Python",
  871. published=datetime.date(2009, 5, 4))
  872. # First check the baseline behavior.
  873. self.assertEqual(router.db_for_read(User), 'other')
  874. self.assertEqual(router.db_for_read(Book), 'other')
  875. self.assertEqual(router.db_for_write(User), 'default')
  876. self.assertEqual(router.db_for_write(Book), 'default')
  877. self.assertTrue(router.allow_relation(dive, dive))
  878. self.assertTrue(router.allow_migrate_model('default', User))
  879. self.assertTrue(router.allow_migrate_model('default', Book))
  880. with override_settings(DATABASE_ROUTERS=[WriteRouter(), AuthRouter(), TestRouter()]):
  881. self.assertEqual(router.db_for_read(User), 'default')
  882. self.assertEqual(router.db_for_read(Book), 'other')
  883. self.assertEqual(router.db_for_write(User), 'writer')
  884. self.assertEqual(router.db_for_write(Book), 'writer')
  885. self.assertTrue(router.allow_relation(dive, dive))
  886. self.assertFalse(router.allow_migrate_model('default', User))
  887. self.assertTrue(router.allow_migrate_model('default', Book))
  888. def test_database_routing(self):
  889. marty = Person.objects.using('default').create(name="Marty Alchin")
  890. pro = Book.objects.using('default').create(title="Pro Django",
  891. published=datetime.date(2008, 12, 16),
  892. editor=marty)
  893. pro.authors.set([marty])
  894. # Create a book and author on the other database
  895. Book.objects.using('other').create(title="Dive into Python",
  896. published=datetime.date(2009, 5, 4))
  897. # An update query will be routed to the default database
  898. Book.objects.filter(title='Pro Django').update(pages=200)
  899. with self.assertRaises(Book.DoesNotExist):
  900. # By default, the get query will be directed to 'other'
  901. Book.objects.get(title='Pro Django')
  902. # But the same query issued explicitly at a database will work.
  903. pro = Book.objects.using('default').get(title='Pro Django')
  904. # Check that the update worked.
  905. self.assertEqual(pro.pages, 200)
  906. # An update query with an explicit using clause will be routed
  907. # to the requested database.
  908. Book.objects.using('other').filter(title='Dive into Python').update(pages=300)
  909. self.assertEqual(Book.objects.get(title='Dive into Python').pages, 300)
  910. # Related object queries stick to the same database
  911. # as the original object, regardless of the router
  912. self.assertEqual(list(pro.authors.values_list('name', flat=True)), ['Marty Alchin'])
  913. self.assertEqual(pro.editor.name, 'Marty Alchin')
  914. # get_or_create is a special case. The get needs to be targeted at
  915. # the write database in order to avoid potential transaction
  916. # consistency problems
  917. book, created = Book.objects.get_or_create(title="Pro Django")
  918. self.assertFalse(created)
  919. book, created = Book.objects.get_or_create(title="Dive Into Python",
  920. defaults={'published': datetime.date(2009, 5, 4)})
  921. self.assertTrue(created)
  922. # Check the head count of objects
  923. self.assertEqual(Book.objects.using('default').count(), 2)
  924. self.assertEqual(Book.objects.using('other').count(), 1)
  925. # If a database isn't specified, the read database is used
  926. self.assertEqual(Book.objects.count(), 1)
  927. # A delete query will also be routed to the default database
  928. Book.objects.filter(pages__gt=150).delete()
  929. # The default database has lost the book.
  930. self.assertEqual(Book.objects.using('default').count(), 1)
  931. self.assertEqual(Book.objects.using('other').count(), 1)
  932. def test_invalid_set_foreign_key_assignment(self):
  933. marty = Person.objects.using('default').create(name="Marty Alchin")
  934. dive = Book.objects.using('other').create(
  935. title="Dive into Python",
  936. published=datetime.date(2009, 5, 4),
  937. )
  938. # Set a foreign key set with an object from a different database
  939. msg = "<Book: Dive into Python> instance isn't saved. Use bulk=False or save the object first."
  940. with self.assertRaisesMessage(ValueError, msg):
  941. marty.edited.set([dive])
  942. def test_foreign_key_cross_database_protection(self):
  943. "Foreign keys can cross databases if they two databases have a common source"
  944. # Create a book and author on the default database
  945. pro = Book.objects.using('default').create(title="Pro Django",
  946. published=datetime.date(2008, 12, 16))
  947. marty = Person.objects.using('default').create(name="Marty Alchin")
  948. # Create a book and author on the other database
  949. dive = Book.objects.using('other').create(title="Dive into Python",
  950. published=datetime.date(2009, 5, 4))
  951. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  952. # Set a foreign key with an object from a different database
  953. try:
  954. dive.editor = marty
  955. except ValueError:
  956. self.fail("Assignment across primary/replica databases with a common source should be ok")
  957. # Database assignments of original objects haven't changed...
  958. self.assertEqual(marty._state.db, 'default')
  959. self.assertEqual(pro._state.db, 'default')
  960. self.assertEqual(dive._state.db, 'other')
  961. self.assertEqual(mark._state.db, 'other')
  962. # ... but they will when the affected object is saved.
  963. dive.save()
  964. self.assertEqual(dive._state.db, 'default')
  965. # ...and the source database now has a copy of any object saved
  966. try:
  967. Book.objects.using('default').get(title='Dive into Python').delete()
  968. except Book.DoesNotExist:
  969. self.fail('Source database should have a copy of saved object')
  970. # This isn't a real primary/replica database, so restore the original from other
  971. dive = Book.objects.using('other').get(title='Dive into Python')
  972. self.assertEqual(dive._state.db, 'other')
  973. # Set a foreign key set with an object from a different database
  974. try:
  975. marty.edited.set([pro, dive], bulk=False)
  976. except ValueError:
  977. self.fail("Assignment across primary/replica databases with a common source should be ok")
  978. # Assignment implies a save, so database assignments of original objects have changed...
  979. self.assertEqual(marty._state.db, 'default')
  980. self.assertEqual(pro._state.db, 'default')
  981. self.assertEqual(dive._state.db, 'default')
  982. self.assertEqual(mark._state.db, 'other')
  983. # ...and the source database now has a copy of any object saved
  984. try:
  985. Book.objects.using('default').get(title='Dive into Python').delete()
  986. except Book.DoesNotExist:
  987. self.fail('Source database should have a copy of saved object')
  988. # This isn't a real primary/replica database, so restore the original from other
  989. dive = Book.objects.using('other').get(title='Dive into Python')
  990. self.assertEqual(dive._state.db, 'other')
  991. # Add to a foreign key set with an object from a different database
  992. try:
  993. marty.edited.add(dive, bulk=False)
  994. except ValueError:
  995. self.fail("Assignment across primary/replica databases with a common source should be ok")
  996. # Add implies a save, so database assignments of original objects have changed...
  997. self.assertEqual(marty._state.db, 'default')
  998. self.assertEqual(pro._state.db, 'default')
  999. self.assertEqual(dive._state.db, 'default')
  1000. self.assertEqual(mark._state.db, 'other')
  1001. # ...and the source database now has a copy of any object saved
  1002. try:
  1003. Book.objects.using('default').get(title='Dive into Python').delete()
  1004. except Book.DoesNotExist:
  1005. self.fail('Source database should have a copy of saved object')
  1006. # This isn't a real primary/replica database, so restore the original from other
  1007. dive = Book.objects.using('other').get(title='Dive into Python')
  1008. # If you assign a FK object when the base object hasn't
  1009. # been saved yet, you implicitly assign the database for the
  1010. # base object.
  1011. chris = Person(name="Chris Mills")
  1012. html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
  1013. # initially, no db assigned
  1014. self.assertEqual(chris._state.db, None)
  1015. self.assertEqual(html5._state.db, None)
  1016. # old object comes from 'other', so the new object is set to use the
  1017. # source of 'other'...
  1018. self.assertEqual(dive._state.db, 'other')
  1019. chris.save()
  1020. dive.editor = chris
  1021. html5.editor = mark
  1022. self.assertEqual(dive._state.db, 'other')
  1023. self.assertEqual(mark._state.db, 'other')
  1024. self.assertEqual(chris._state.db, 'default')
  1025. self.assertEqual(html5._state.db, 'default')
  1026. # This also works if you assign the FK in the constructor
  1027. water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark)
  1028. self.assertEqual(water._state.db, 'default')
  1029. # For the remainder of this test, create a copy of 'mark' in the
  1030. # 'default' database to prevent integrity errors on backends that
  1031. # don't defer constraints checks until the end of the transaction
  1032. mark.save(using='default')
  1033. # This moved 'mark' in the 'default' database, move it back in 'other'
  1034. mark.save(using='other')
  1035. self.assertEqual(mark._state.db, 'other')
  1036. # If you create an object through a FK relation, it will be
  1037. # written to the write database, even if the original object
  1038. # was on the read database
  1039. cheesecake = mark.edited.create(title='Dive into Cheesecake', published=datetime.date(2010, 3, 15))
  1040. self.assertEqual(cheesecake._state.db, 'default')
  1041. # Same goes for get_or_create, regardless of whether getting or creating
  1042. cheesecake, created = mark.edited.get_or_create(
  1043. title='Dive into Cheesecake',
  1044. published=datetime.date(2010, 3, 15),
  1045. )
  1046. self.assertEqual(cheesecake._state.db, 'default')
  1047. puddles, created = mark.edited.get_or_create(title='Dive into Puddles', published=datetime.date(2010, 3, 15))
  1048. self.assertEqual(puddles._state.db, 'default')
  1049. def test_m2m_cross_database_protection(self):
  1050. "M2M relations can cross databases if the database share a source"
  1051. # Create books and authors on the inverse to the usual database
  1052. pro = Book.objects.using('other').create(pk=1, title="Pro Django",
  1053. published=datetime.date(2008, 12, 16))
  1054. marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
  1055. dive = Book.objects.using('default').create(pk=2, title="Dive into Python",
  1056. published=datetime.date(2009, 5, 4))
  1057. mark = Person.objects.using('default').create(pk=2, name="Mark Pilgrim")
  1058. # Now save back onto the usual database.
  1059. # This simulates primary/replica - the objects exist on both database,
  1060. # but the _state.db is as it is for all other tests.
  1061. pro.save(using='default')
  1062. marty.save(using='default')
  1063. dive.save(using='other')
  1064. mark.save(using='other')
  1065. # Check that we have 2 of both types of object on both databases
  1066. self.assertEqual(Book.objects.using('default').count(), 2)
  1067. self.assertEqual(Book.objects.using('other').count(), 2)
  1068. self.assertEqual(Person.objects.using('default').count(), 2)
  1069. self.assertEqual(Person.objects.using('other').count(), 2)
  1070. # Set a m2m set with an object from a different database
  1071. try:
  1072. marty.book_set.set([pro, dive])
  1073. except ValueError:
  1074. self.fail("Assignment across primary/replica databases with a common source should be ok")
  1075. # Database assignments don't change
  1076. self.assertEqual(marty._state.db, 'default')
  1077. self.assertEqual(pro._state.db, 'default')
  1078. self.assertEqual(dive._state.db, 'other')
  1079. self.assertEqual(mark._state.db, 'other')
  1080. # All m2m relations should be saved on the default database
  1081. self.assertEqual(Book.authors.through.objects.using('default').count(), 2)
  1082. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  1083. # Reset relations
  1084. Book.authors.through.objects.using('default').delete()
  1085. # Add to an m2m with an object from a different database
  1086. try:
  1087. marty.book_set.add(dive)
  1088. except ValueError:
  1089. self.fail("Assignment across primary/replica databases with a common source should be ok")
  1090. # Database assignments don't change
  1091. self.assertEqual(marty._state.db, 'default')
  1092. self.assertEqual(pro._state.db, 'default')
  1093. self.assertEqual(dive._state.db, 'other')
  1094. self.assertEqual(mark._state.db, 'other')
  1095. # All m2m relations should be saved on the default database
  1096. self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
  1097. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  1098. # Reset relations
  1099. Book.authors.through.objects.using('default').delete()
  1100. # Set a reverse m2m with an object from a different database
  1101. try:
  1102. dive.authors.set([mark, marty])
  1103. except ValueError:
  1104. self.fail("Assignment across primary/replica databases with a common source should be ok")
  1105. # Database assignments don't change
  1106. self.assertEqual(marty._state.db, 'default')
  1107. self.assertEqual(pro._state.db, 'default')
  1108. self.assertEqual(dive._state.db, 'other')
  1109. self.assertEqual(mark._state.db, 'other')
  1110. # All m2m relations should be saved on the default database
  1111. self.assertEqual(Book.authors.through.objects.using('default').count(), 2)
  1112. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  1113. # Reset relations
  1114. Book.authors.through.objects.using('default').delete()
  1115. self.assertEqual(Book.authors.through.objects.using('default').count(), 0)
  1116. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  1117. # Add to a reverse m2m with an object from a different database
  1118. try:
  1119. dive.authors.add(marty)
  1120. except ValueError:
  1121. self.fail("Assignment across primary/replica databases with a common source should be ok")
  1122. # Database assignments don't change
  1123. self.assertEqual(marty._state.db, 'default')
  1124. self.assertEqual(pro._state.db, 'default')
  1125. self.assertEqual(dive._state.db, 'other')
  1126. self.assertEqual(mark._state.db, 'other')
  1127. # All m2m relations should be saved on the default database
  1128. self.assertEqual(Book.authors.through.objects.using('default').count(), 1)
  1129. self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
  1130. # If you create an object through a M2M relation, it will be
  1131. # written to the write database, even if the original object
  1132. # was on the read database
  1133. alice = dive.authors.create(name='Alice')
  1134. self.assertEqual(alice._state.db, 'default')
  1135. # Same goes for get_or_create, regardless of whether getting or creating
  1136. alice, created = dive.authors.get_or_create(name='Alice')
  1137. self.assertEqual(alice._state.db, 'default')
  1138. bob, created = dive.authors.get_or_create(name='Bob')
  1139. self.assertEqual(bob._state.db, 'default')
  1140. def test_o2o_cross_database_protection(self):
  1141. "Operations that involve sharing FK objects across databases raise an error"
  1142. # Create a user and profile on the default database
  1143. alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com')
  1144. # Create a user and profile on the other database
  1145. bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com')
  1146. # Set a one-to-one relation with an object from a different database
  1147. alice_profile = UserProfile.objects.create(user=alice, flavor='chocolate')
  1148. try:
  1149. bob.userprofile = alice_profile
  1150. except ValueError:
  1151. self.fail("Assignment across primary/replica databases with a common source should be ok")
  1152. # Database assignments of original objects haven't changed...
  1153. self.assertEqual(alice._state.db, 'default')
  1154. self.assertEqual(alice_profile._state.db, 'default')
  1155. self.assertEqual(bob._state.db, 'other')
  1156. # ... but they will when the affected object is saved.
  1157. bob.save()
  1158. self.assertEqual(bob._state.db, 'default')
  1159. def test_generic_key_cross_database_protection(self):
  1160. "Generic Key operations can span databases if they share a source"
  1161. # Create a book and author on the default database
  1162. pro = Book.objects.using(
  1163. 'default').create(title="Pro Django", published=datetime.date(2008, 12, 16))
  1164. review1 = Review.objects.using(
  1165. 'default').create(source="Python Monthly", content_object=pro)
  1166. # Create a book and author on the other database
  1167. dive = Book.objects.using(
  1168. 'other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
  1169. review2 = Review.objects.using(
  1170. 'other').create(source="Python Weekly", content_object=dive)
  1171. # Set a generic foreign key with an object from a different database
  1172. try:
  1173. review1.content_object = dive
  1174. except ValueError:
  1175. self.fail("Assignment across primary/replica databases with a common source should be ok")
  1176. # Database assignments of original objects haven't changed...
  1177. self.assertEqual(pro._state.db, 'default')
  1178. self.assertEqual(review1._state.db, 'default')
  1179. self.assertEqual(dive._state.db, 'other')
  1180. self.assertEqual(review2._state.db, 'other')
  1181. # ... but they will when the affected object is saved.
  1182. dive.save()
  1183. self.assertEqual(review1._state.db, 'default')
  1184. self.assertEqual(dive._state.db, 'default')
  1185. # ...and the source database now has a copy of any object saved
  1186. try:
  1187. Book.objects.using('default').get(title='Dive into Python').delete()
  1188. except Book.DoesNotExist:
  1189. self.fail('Source database should have a copy of saved object')
  1190. # This isn't a real primary/replica database, so restore the original from other
  1191. dive = Book.objects.using('other').get(title='Dive into Python')
  1192. self.assertEqual(dive._state.db, 'other')
  1193. # Add to a generic foreign key set with an object from a different database
  1194. try:
  1195. dive.reviews.add(review1)
  1196. except ValueError:
  1197. self.fail("Assignment across primary/replica databases with a common source should be ok")
  1198. # Database assignments of original objects haven't changed...
  1199. self.assertEqual(pro._state.db, 'default')
  1200. self.assertEqual(review1._state.db, 'default')
  1201. self.assertEqual(dive._state.db, 'other')
  1202. self.assertEqual(review2._state.db, 'other')
  1203. # ... but they will when the affected object is saved.
  1204. dive.save()
  1205. self.assertEqual(dive._state.db, 'default')
  1206. # ...and the source database now has a copy of any object saved
  1207. try:
  1208. Book.objects.using('default').get(title='Dive into Python').delete()
  1209. except Book.DoesNotExist:
  1210. self.fail('Source database should have a copy of saved object')
  1211. # BUT! if you assign a FK object when the base object hasn't
  1212. # been saved yet, you implicitly assign the database for the
  1213. # base object.
  1214. review3 = Review(source="Python Daily")
  1215. # initially, no db assigned
  1216. self.assertEqual(review3._state.db, None)
  1217. # Dive comes from 'other', so review3 is set to use the source of 'other'...
  1218. review3.content_object = dive
  1219. self.assertEqual(review3._state.db, 'default')
  1220. # If you create an object through a M2M relation, it will be
  1221. # written to the write database, even if the original object
  1222. # was on the read database
  1223. dive = Book.objects.using('other').get(title='Dive into Python')
  1224. nyt = dive.reviews.create(source="New York Times", content_object=dive)
  1225. self.assertEqual(nyt._state.db, 'default')
  1226. def test_m2m_managers(self):
  1227. "M2M relations are represented by managers, and can be controlled like managers"
  1228. pro = Book.objects.using('other').create(pk=1, title="Pro Django",
  1229. published=datetime.date(2008, 12, 16))
  1230. marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
  1231. self.assertEqual(pro.authors.db, 'other')
  1232. self.assertEqual(pro.authors.db_manager('default').db, 'default')
  1233. self.assertEqual(pro.authors.db_manager('default').all().db, 'default')
  1234. self.assertEqual(marty.book_set.db, 'other')
  1235. self.assertEqual(marty.book_set.db_manager('default').db, 'default')
  1236. self.assertEqual(marty.book_set.db_manager('default').all().db, 'default')
  1237. def test_foreign_key_managers(self):
  1238. "FK reverse relations are represented by managers, and can be controlled like managers"
  1239. marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
  1240. Book.objects.using('other').create(pk=1, title="Pro Django",
  1241. published=datetime.date(2008, 12, 16),
  1242. editor=marty)
  1243. self.assertEqual(marty.edited.db, 'other')
  1244. self.assertEqual(marty.edited.db_manager('default').db, 'default')
  1245. self.assertEqual(marty.edited.db_manager('default').all().db, 'default')
  1246. def test_generic_key_managers(self):
  1247. "Generic key relations are represented by managers, and can be controlled like managers"
  1248. pro = Book.objects.using('other').create(title="Pro Django",
  1249. published=datetime.date(2008, 12, 16))
  1250. Review.objects.using('other').create(source="Python Monthly",
  1251. content_object=pro)
  1252. self.assertEqual(pro.reviews.db, 'other')
  1253. self.assertEqual(pro.reviews.db_manager('default').db, 'default')
  1254. self.assertEqual(pro.reviews.db_manager('default').all().db, 'default')
  1255. def test_subquery(self):
  1256. """Make sure as_sql works with subqueries and primary/replica."""
  1257. # Create a book and author on the other database
  1258. mark = Person.objects.using('other').create(name="Mark Pilgrim")
  1259. Book.objects.using('other').create(title="Dive into Python",
  1260. published=datetime.date(2009, 5, 4),
  1261. editor=mark)
  1262. sub = Person.objects.filter(name='Mark Pilgrim')
  1263. qs = Book.objects.filter(editor__in=sub)
  1264. # When you call __str__ on the query object, it doesn't know about using
  1265. # so it falls back to the default. Don't let routing instructions
  1266. # force the subquery to an incompatible database.
  1267. str(qs.query)
  1268. # If you evaluate the query, it should work, running on 'other'
  1269. self.assertEqual(list(qs.values_list('title', flat=True)), ['Dive into Python'])
  1270. def test_deferred_models(self):
  1271. mark_def = Person.objects.using('default').create(name="Mark Pilgrim")
  1272. mark_other = Person.objects.using('other').create(name="Mark Pilgrim")
  1273. orig_b = Book.objects.using('other').create(title="Dive into Python",
  1274. published=datetime.date(2009, 5, 4),
  1275. editor=mark_other)
  1276. b = Book.objects.using('other').only('title').get(pk=orig_b.pk)
  1277. self.assertEqual(b.published, datetime.date(2009, 5, 4))
  1278. b = Book.objects.using('other').only('title').get(pk=orig_b.pk)
  1279. b.editor = mark_def
  1280. b.save(using='default')
  1281. self.assertEqual(Book.objects.using('default').get(pk=b.pk).published,
  1282. datetime.date(2009, 5, 4))
  1283. @override_settings(DATABASE_ROUTERS=[AuthRouter()])
  1284. class AuthTestCase(TestCase):
  1285. multi_db = True
  1286. def test_auth_manager(self):
  1287. "The methods on the auth manager obey database hints"
  1288. # Create one user using default allocation policy
  1289. User.objects.create_user('alice', 'alice@example.com')
  1290. # Create another user, explicitly specifying the database
  1291. User.objects.db_manager('default').create_user('bob', 'bob@example.com')
  1292. # The second user only exists on the other database
  1293. alice = User.objects.using('other').get(username='alice')
  1294. self.assertEqual(alice.username, 'alice')
  1295. self.assertEqual(alice._state.db, 'other')
  1296. self.assertRaises(User.DoesNotExist, User.objects.using('default').get, username='alice')
  1297. # The second user only exists on the default database
  1298. bob = User.objects.using('default').get(username='bob')
  1299. self.assertEqual(bob.username, 'bob')
  1300. self.assertEqual(bob._state.db, 'default')
  1301. self.assertRaises(User.DoesNotExist, User.objects.using('other').get, username='bob')
  1302. # That is... there is one user on each database
  1303. self.assertEqual(User.objects.using('default').count(), 1)
  1304. self.assertEqual(User.objects.using('other').count(), 1)
  1305. def test_dumpdata(self):
  1306. "Check that dumpdata honors allow_migrate restrictions on the router"
  1307. User.objects.create_user('alice', 'alice@example.com')
  1308. User.objects.db_manager('default').create_user('bob', 'bob@example.com')
  1309. # Check that dumping the default database doesn't try to include auth
  1310. # because allow_migrate prohibits auth on default
  1311. new_io = StringIO()
  1312. management.call_command('dumpdata', 'auth', format='json', database='default', stdout=new_io)
  1313. command_output = new_io.getvalue().strip()
  1314. self.assertEqual(command_output, '[]')
  1315. # Check that dumping the other database does include auth
  1316. new_io = StringIO()
  1317. management.call_command('dumpdata', 'auth', format='json', database='other', stdout=new_io)
  1318. command_output = new_io.getvalue().strip()
  1319. self.assertIn('"email": "alice@example.com"', command_output)
  1320. class AntiPetRouter(object):
  1321. # A router that only expresses an opinion on migrate,
  1322. # passing pets to the 'other' database
  1323. def allow_migrate(self, db, app_label, model_name=None, **hints):
  1324. if db == 'other':
  1325. return model_name == 'pet'
  1326. else:
  1327. return model_name != 'pet'
  1328. class FixtureTestCase(TestCase):
  1329. multi_db = True
  1330. fixtures = ['multidb-common', 'multidb']
  1331. @override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
  1332. def test_fixture_loading(self):
  1333. "Multi-db fixtures are loaded correctly"
  1334. # Check that "Pro Django" exists on the default database, but not on other database
  1335. try:
  1336. Book.objects.get(title="Pro Django")
  1337. Book.objects.using('default').get(title="Pro Django")
  1338. except Book.DoesNotExist:
  1339. self.fail('"Pro Django" should exist on default database')
  1340. self.assertRaises(
  1341. Book.DoesNotExist,
  1342. Book.objects.using('other').get,
  1343. title="Pro Django"
  1344. )
  1345. # Check that "Dive into Python" exists on the default database, but not on other database
  1346. try:
  1347. Book.objects.using('other').get(title="Dive into Python")
  1348. except Book.DoesNotExist:
  1349. self.fail('"Dive into Python" should exist on other database')
  1350. self.assertRaises(
  1351. Book.DoesNotExist,
  1352. Book.objects.get,
  1353. title="Dive into Python"
  1354. )
  1355. self.assertRaises(
  1356. Book.DoesNotExist,
  1357. Book.objects.using('default').get,
  1358. title="Dive into Python"
  1359. )
  1360. # Check that "Definitive Guide" exists on the both databases
  1361. try:
  1362. Book.objects.get(title="The Definitive Guide to Django")
  1363. Book.objects.using('default').get(title="The Definitive Guide to Django")
  1364. Book.objects.using('other').get(title="The Definitive Guide to Django")
  1365. except Book.DoesNotExist:
  1366. self.fail('"The Definitive Guide to Django" should exist on both databases')
  1367. @override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
  1368. def test_pseudo_empty_fixtures(self):
  1369. """
  1370. A fixture can contain entries, but lead to nothing in the database;
  1371. this shouldn't raise an error (#14068).
  1372. """
  1373. new_io = StringIO()
  1374. management.call_command('loaddata', 'pets', stdout=new_io, stderr=new_io)
  1375. command_output = new_io.getvalue().strip()
  1376. # No objects will actually be loaded
  1377. self.assertEqual(command_output, "Installed 0 object(s) (of 2) from 1 fixture(s)")
  1378. class PickleQuerySetTestCase(TestCase):
  1379. multi_db = True
  1380. def test_pickling(self):
  1381. for db in connections:
  1382. Book.objects.using(db).create(title='Dive into Python', published=datetime.date(2009, 5, 4))
  1383. qs = Book.objects.all()
  1384. self.assertEqual(qs.db, pickle.loads(pickle.dumps(qs)).db)
  1385. class DatabaseReceiver(object):
  1386. """
  1387. Used in the tests for the database argument in signals (#13552)
  1388. """
  1389. def __call__(self, signal, sender, **kwargs):
  1390. self._database = kwargs['using']
  1391. class WriteToOtherRouter(object):
  1392. """
  1393. A router that sends all writes to the other database.
  1394. """
  1395. def db_for_write(self, model, **hints):
  1396. return "other"
  1397. class SignalTests(TestCase):
  1398. multi_db = True
  1399. def override_router(self):
  1400. return override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()])
  1401. def test_database_arg_save_and_delete(self):
  1402. """
  1403. Tests that the pre/post_save signal contains the correct database.
  1404. (#13552)
  1405. """
  1406. # Make some signal receivers
  1407. pre_save_receiver = DatabaseReceiver()
  1408. post_save_receiver = DatabaseReceiver()
  1409. pre_delete_receiver = DatabaseReceiver()
  1410. post_delete_receiver = DatabaseReceiver()
  1411. # Make model and connect receivers
  1412. signals.pre_save.connect(sender=Person, receiver=pre_save_receiver)
  1413. signals.post_save.connect(sender=Person, receiver=post_save_receiver)
  1414. signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
  1415. signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
  1416. p = Person.objects.create(name='Darth Vader')
  1417. # Save and test receivers got calls
  1418. p.save()
  1419. self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
  1420. self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
  1421. # Delete, and test
  1422. p.delete()
  1423. self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
  1424. self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
  1425. # Save again to a different database
  1426. p.save(using="other")
  1427. self.assertEqual(pre_save_receiver._database, "other")
  1428. self.assertEqual(post_save_receiver._database, "other")
  1429. # Delete, and test
  1430. p.delete(using="other")
  1431. self.assertEqual(pre_delete_receiver._database, "other")
  1432. self.assertEqual(post_delete_receiver._database, "other")
  1433. signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver)
  1434. signals.post_save.disconnect(sender=Person, receiver=post_save_receiver)
  1435. signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver)
  1436. signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver)
  1437. def test_database_arg_m2m(self):
  1438. """
  1439. Test that the m2m_changed signal has a correct database arg (#13552)
  1440. """
  1441. # Make a receiver
  1442. receiver = DatabaseReceiver()
  1443. # Connect it
  1444. signals.m2m_changed.connect(receiver=receiver)
  1445. # Create the models that will be used for the tests
  1446. b = Book.objects.create(title="Pro Django",
  1447. published=datetime.date(2008, 12, 16))
  1448. p = Person.objects.create(name="Marty Alchin")
  1449. # Create a copy of the models on the 'other' database to prevent
  1450. # integrity errors on backends that don't defer constraints checks
  1451. Book.objects.using('other').create(pk=b.pk, title=b.title,
  1452. published=b.published)
  1453. Person.objects.using('other').create(pk=p.pk, name=p.name)
  1454. # Test addition
  1455. b.authors.add(p)
  1456. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1457. with self.override_router():
  1458. b.authors.add(p)
  1459. self.assertEqual(receiver._database, "other")
  1460. # Test removal
  1461. b.authors.remove(p)
  1462. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1463. with self.override_router():
  1464. b.authors.remove(p)
  1465. self.assertEqual(receiver._database, "other")
  1466. # Test addition in reverse
  1467. p.book_set.add(b)
  1468. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1469. with self.override_router():
  1470. p.book_set.add(b)
  1471. self.assertEqual(receiver._database, "other")
  1472. # Test clearing
  1473. b.authors.clear()
  1474. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1475. with self.override_router():
  1476. b.authors.clear()
  1477. self.assertEqual(receiver._database, "other")
  1478. class AttributeErrorRouter(object):
  1479. "A router to test the exception handling of ConnectionRouter"
  1480. def db_for_read(self, model, **hints):
  1481. raise AttributeError
  1482. def db_for_write(self, model, **hints):
  1483. raise AttributeError
  1484. class RouterAttributeErrorTestCase(TestCase):
  1485. multi_db = True
  1486. def override_router(self):
  1487. return override_settings(DATABASE_ROUTERS=[AttributeErrorRouter()])
  1488. def test_attribute_error_read(self):
  1489. "Check that the AttributeError from AttributeErrorRouter bubbles up"
  1490. b = Book.objects.create(title="Pro Django",
  1491. published=datetime.date(2008, 12, 16))
  1492. with self.override_router():
  1493. self.assertRaises(AttributeError, Book.objects.get, pk=b.pk)
  1494. def test_attribute_error_save(self):
  1495. "Check that the AttributeError from AttributeErrorRouter bubbles up"
  1496. dive = Book()
  1497. dive.title = "Dive into Python"
  1498. dive.published = datetime.date(2009, 5, 4)
  1499. with self.override_router():
  1500. self.assertRaises(AttributeError, dive.save)
  1501. def test_attribute_error_delete(self):
  1502. "Check that the AttributeError from AttributeErrorRouter bubbles up"
  1503. b = Book.objects.create(title="Pro Django",
  1504. published=datetime.date(2008, 12, 16))
  1505. p = Person.objects.create(name="Marty Alchin")
  1506. b.authors.set([p])
  1507. b.editor = p
  1508. with self.override_router():
  1509. self.assertRaises(AttributeError, b.delete)
  1510. def test_attribute_error_m2m(self):
  1511. "Check that the AttributeError from AttributeErrorRouter bubbles up"
  1512. b = Book.objects.create(title="Pro Django",
  1513. published=datetime.date(2008, 12, 16))
  1514. p = Person.objects.create(name="Marty Alchin")
  1515. with self.override_router():
  1516. with self.assertRaises(AttributeError):
  1517. b.authors.set([p])
  1518. class ModelMetaRouter(object):
  1519. "A router to ensure model arguments are real model classes"
  1520. def db_for_write(self, model, **hints):
  1521. if not hasattr(model, '_meta'):
  1522. raise ValueError
  1523. @override_settings(DATABASE_ROUTERS=[ModelMetaRouter()])
  1524. class RouterModelArgumentTestCase(TestCase):
  1525. multi_db = True
  1526. def test_m2m_collection(self):
  1527. b = Book.objects.create(title="Pro Django",
  1528. published=datetime.date(2008, 12, 16))
  1529. p = Person.objects.create(name="Marty Alchin")
  1530. # test add
  1531. b.authors.add(p)
  1532. # test remove
  1533. b.authors.remove(p)
  1534. # test clear
  1535. b.authors.clear()
  1536. # test setattr
  1537. b.authors.set([p])
  1538. # test M2M collection
  1539. b.delete()
  1540. def test_foreignkey_collection(self):
  1541. person = Person.objects.create(name='Bob')
  1542. Pet.objects.create(owner=person, name='Wart')
  1543. # test related FK collection
  1544. person.delete()
  1545. class SyncOnlyDefaultDatabaseRouter(object):
  1546. def allow_migrate(self, db, app_label, **hints):
  1547. return db == DEFAULT_DB_ALIAS
  1548. class MigrateTestCase(TestCase):
  1549. available_apps = [
  1550. 'multiple_database',
  1551. 'django.contrib.auth',
  1552. 'django.contrib.contenttypes'
  1553. ]
  1554. multi_db = True
  1555. def test_migrate_to_other_database(self):
  1556. """Regression test for #16039: migrate with --database option."""
  1557. cts = ContentType.objects.using('other').filter(app_label='multiple_database')
  1558. count = cts.count()
  1559. self.assertGreater(count, 0)
  1560. cts.delete()
  1561. management.call_command('migrate', verbosity=0, interactive=False, database='other')
  1562. self.assertEqual(cts.count(), count)
  1563. def test_migrate_to_other_database_with_router(self):
  1564. """Regression test for #16039: migrate with --database option."""
  1565. cts = ContentType.objects.using('other').filter(app_label='multiple_database')
  1566. cts.delete()
  1567. with override_settings(DATABASE_ROUTERS=[SyncOnlyDefaultDatabaseRouter()]):
  1568. management.call_command('migrate', verbosity=0, interactive=False, database='other')
  1569. self.assertEqual(cts.count(), 0)
  1570. class RouterUsed(Exception):
  1571. WRITE = 'write'
  1572. def __init__(self, mode, model, hints):
  1573. self.mode = mode
  1574. self.model = model
  1575. self.hints = hints
  1576. class RouteForWriteTestCase(TestCase):
  1577. multi_db = True
  1578. class WriteCheckRouter(object):
  1579. def db_for_write(self, model, **hints):
  1580. raise RouterUsed(mode=RouterUsed.WRITE, model=model, hints=hints)
  1581. def override_router(self):
  1582. return override_settings(DATABASE_ROUTERS=[RouteForWriteTestCase.WriteCheckRouter()])
  1583. def test_fk_delete(self):
  1584. owner = Person.objects.create(name='Someone')
  1585. pet = Pet.objects.create(name='fido', owner=owner)
  1586. try:
  1587. with self.override_router():
  1588. pet.owner.delete()
  1589. self.fail('db_for_write() not invoked on router')
  1590. except RouterUsed as e:
  1591. self.assertEqual(e.mode, RouterUsed.WRITE)
  1592. self.assertEqual(e.model, Person)
  1593. self.assertEqual(e.hints, {'instance': owner})
  1594. def test_reverse_fk_delete(self):
  1595. owner = Person.objects.create(name='Someone')
  1596. to_del_qs = owner.pet_set.all()
  1597. try:
  1598. with self.override_router():
  1599. to_del_qs.delete()
  1600. self.fail('db_for_write() not invoked on router')
  1601. except RouterUsed as e:
  1602. self.assertEqual(e.mode, RouterUsed.WRITE)
  1603. self.assertEqual(e.model, Pet)
  1604. self.assertEqual(e.hints, {'instance': owner})
  1605. def test_reverse_fk_get_or_create(self):
  1606. owner = Person.objects.create(name='Someone')
  1607. try:
  1608. with self.override_router():
  1609. owner.pet_set.get_or_create(name='fido')
  1610. self.fail('db_for_write() not invoked on router')
  1611. except RouterUsed as e:
  1612. self.assertEqual(e.mode, RouterUsed.WRITE)
  1613. self.assertEqual(e.model, Pet)
  1614. self.assertEqual(e.hints, {'instance': owner})
  1615. def test_reverse_fk_update(self):
  1616. owner = Person.objects.create(name='Someone')
  1617. Pet.objects.create(name='fido', owner=owner)
  1618. try:
  1619. with self.override_router():
  1620. owner.pet_set.update(name='max')
  1621. self.fail('db_for_write() not invoked on router')
  1622. except RouterUsed as e:
  1623. self.assertEqual(e.mode, RouterUsed.WRITE)
  1624. self.assertEqual(e.model, Pet)
  1625. self.assertEqual(e.hints, {'instance': owner})
  1626. def test_m2m_add(self):
  1627. auth = Person.objects.create(name='Someone')
  1628. book = Book.objects.create(title="Pro Django",
  1629. published=datetime.date(2008, 12, 16))
  1630. try:
  1631. with self.override_router():
  1632. book.authors.add(auth)
  1633. self.fail('db_for_write() not invoked on router')
  1634. except RouterUsed as e:
  1635. self.assertEqual(e.mode, RouterUsed.WRITE)
  1636. self.assertEqual(e.model, Book.authors.through)
  1637. self.assertEqual(e.hints, {'instance': book})
  1638. def test_m2m_clear(self):
  1639. auth = Person.objects.create(name='Someone')
  1640. book = Book.objects.create(title="Pro Django",
  1641. published=datetime.date(2008, 12, 16))
  1642. book.authors.add(auth)
  1643. try:
  1644. with self.override_router():
  1645. book.authors.clear()
  1646. self.fail('db_for_write() not invoked on router')
  1647. except RouterUsed as e:
  1648. self.assertEqual(e.mode, RouterUsed.WRITE)
  1649. self.assertEqual(e.model, Book.authors.through)
  1650. self.assertEqual(e.hints, {'instance': book})
  1651. def test_m2m_delete(self):
  1652. auth = Person.objects.create(name='Someone')
  1653. book = Book.objects.create(title="Pro Django",
  1654. published=datetime.date(2008, 12, 16))
  1655. book.authors.add(auth)
  1656. try:
  1657. with self.override_router():
  1658. book.authors.all().delete()
  1659. self.fail('db_for_write() not invoked on router')
  1660. except RouterUsed as e:
  1661. self.assertEqual(e.mode, RouterUsed.WRITE)
  1662. self.assertEqual(e.model, Person)
  1663. self.assertEqual(e.hints, {'instance': book})
  1664. def test_m2m_get_or_create(self):
  1665. Person.objects.create(name='Someone')
  1666. book = Book.objects.create(title="Pro Django",
  1667. published=datetime.date(2008, 12, 16))
  1668. try:
  1669. with self.override_router():
  1670. book.authors.get_or_create(name='Someone else')
  1671. self.fail('db_for_write() not invoked on router')
  1672. except RouterUsed as e:
  1673. self.assertEqual(e.mode, RouterUsed.WRITE)
  1674. self.assertEqual(e.model, Book)
  1675. self.assertEqual(e.hints, {'instance': book})
  1676. def test_m2m_remove(self):
  1677. auth = Person.objects.create(name='Someone')
  1678. book = Book.objects.create(title="Pro Django",
  1679. published=datetime.date(2008, 12, 16))
  1680. book.authors.add(auth)
  1681. try:
  1682. with self.override_router():
  1683. book.authors.remove(auth)
  1684. self.fail('db_for_write() not invoked on router')
  1685. except RouterUsed as e:
  1686. self.assertEqual(e.mode, RouterUsed.WRITE)
  1687. self.assertEqual(e.model, Book.authors.through)
  1688. self.assertEqual(e.hints, {'instance': book})
  1689. def test_m2m_update(self):
  1690. auth = Person.objects.create(name='Someone')
  1691. book = Book.objects.create(title="Pro Django",
  1692. published=datetime.date(2008, 12, 16))
  1693. book.authors.add(auth)
  1694. try:
  1695. with self.override_router():
  1696. book.authors.all().update(name='Different')
  1697. self.fail('db_for_write() not invoked on router')
  1698. except RouterUsed as e:
  1699. self.assertEqual(e.mode, RouterUsed.WRITE)
  1700. self.assertEqual(e.model, Person)
  1701. self.assertEqual(e.hints, {'instance': book})
  1702. def test_reverse_m2m_add(self):
  1703. auth = Person.objects.create(name='Someone')
  1704. book = Book.objects.create(title="Pro Django",
  1705. published=datetime.date(2008, 12, 16))
  1706. try:
  1707. with self.override_router():
  1708. auth.book_set.add(book)
  1709. self.fail('db_for_write() not invoked on router')
  1710. except RouterUsed as e:
  1711. self.assertEqual(e.mode, RouterUsed.WRITE)
  1712. self.assertEqual(e.model, Book.authors.through)
  1713. self.assertEqual(e.hints, {'instance': auth})
  1714. def test_reverse_m2m_clear(self):
  1715. auth = Person.objects.create(name='Someone')
  1716. book = Book.objects.create(title="Pro Django",
  1717. published=datetime.date(2008, 12, 16))
  1718. book.authors.add(auth)
  1719. try:
  1720. with self.override_router():
  1721. auth.book_set.clear()
  1722. self.fail('db_for_write() not invoked on router')
  1723. except RouterUsed as e:
  1724. self.assertEqual(e.mode, RouterUsed.WRITE)
  1725. self.assertEqual(e.model, Book.authors.through)
  1726. self.assertEqual(e.hints, {'instance': auth})
  1727. def test_reverse_m2m_delete(self):
  1728. auth = Person.objects.create(name='Someone')
  1729. book = Book.objects.create(title="Pro Django",
  1730. published=datetime.date(2008, 12, 16))
  1731. book.authors.add(auth)
  1732. try:
  1733. with self.override_router():
  1734. auth.book_set.all().delete()
  1735. self.fail('db_for_write() not invoked on router')
  1736. except RouterUsed as e:
  1737. self.assertEqual(e.mode, RouterUsed.WRITE)
  1738. self.assertEqual(e.model, Book)
  1739. self.assertEqual(e.hints, {'instance': auth})
  1740. def test_reverse_m2m_get_or_create(self):
  1741. auth = Person.objects.create(name='Someone')
  1742. Book.objects.create(title="Pro Django",
  1743. published=datetime.date(2008, 12, 16))
  1744. try:
  1745. with self.override_router():
  1746. auth.book_set.get_or_create(title="New Book", published=datetime.datetime.now())
  1747. self.fail('db_for_write() not invoked on router')
  1748. except RouterUsed as e:
  1749. self.assertEqual(e.mode, RouterUsed.WRITE)
  1750. self.assertEqual(e.model, Person)
  1751. self.assertEqual(e.hints, {'instance': auth})
  1752. def test_reverse_m2m_remove(self):
  1753. auth = Person.objects.create(name='Someone')
  1754. book = Book.objects.create(title="Pro Django",
  1755. published=datetime.date(2008, 12, 16))
  1756. book.authors.add(auth)
  1757. try:
  1758. with self.override_router():
  1759. auth.book_set.remove(book)
  1760. self.fail('db_for_write() not invoked on router')
  1761. except RouterUsed as e:
  1762. self.assertEqual(e.mode, RouterUsed.WRITE)
  1763. self.assertEqual(e.model, Book.authors.through)
  1764. self.assertEqual(e.hints, {'instance': auth})
  1765. def test_reverse_m2m_update(self):
  1766. auth = Person.objects.create(name='Someone')
  1767. book = Book.objects.create(title="Pro Django",
  1768. published=datetime.date(2008, 12, 16))
  1769. book.authors.add(auth)
  1770. try:
  1771. with self.override_router():
  1772. auth.book_set.all().update(title='Different')
  1773. self.fail('db_for_write() not invoked on router')
  1774. except RouterUsed as e:
  1775. self.assertEqual(e.mode, RouterUsed.WRITE)
  1776. self.assertEqual(e.model, Book)
  1777. self.assertEqual(e.hints, {'instance': auth})