tests.py 93 KB

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