tests.py 86 KB

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