tests.py 95 KB

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