tests.py 91 KB

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