Merge lp:~cjwatson/launchpad/kill-old-switchdbuser into lp:launchpad

Proposed by Colin Watson on 2012-01-20
Status: Merged
Approved by: Benji York on 2012-01-23
Approved revision: no longer in the source branch.
Merged at revision: 14720
Proposed branch: lp:~cjwatson/launchpad/kill-old-switchdbuser
Merge into: lp:launchpad
Diff against target: 5712 lines (+826/-1110)
107 files modified
lib/lp/answers/tests/emailinterface.txt (+16/-21)
lib/lp/archivepublisher/tests/test_ftparchive.py (+2/-1)
lib/lp/archivepublisher/tests/test_generate_ppa_htaccess.py (+18/-24)
lib/lp/archivepublisher/tests/test_publisher_documentation.py (+2/-1)
lib/lp/archiveuploader/tests/nascentupload-announcements.txt (+2/-2)
lib/lp/archiveuploader/tests/nascentupload-closing-bugs.txt (+3/-7)
lib/lp/archiveuploader/tests/nascentupload-ddebs.txt (+10/-15)
lib/lp/archiveuploader/tests/nascentupload-packageset.txt (+8/-14)
lib/lp/archiveuploader/tests/nascentupload.txt (+17/-27)
lib/lp/archiveuploader/tests/test_nascentupload_documentation.py (+2/-1)
lib/lp/archiveuploader/tests/test_ppauploadprocessor.py (+4/-7)
lib/lp/archiveuploader/tests/test_uploadprocessor.py (+3/-5)
lib/lp/bugs/doc/bug-private-by-default.txt (+3/-2)
lib/lp/bugs/doc/bug-watch-activity.txt (+3/-9)
lib/lp/bugs/doc/bugnotification-sending.txt (+1/-16)
lib/lp/bugs/doc/bugtracker-person.txt (+7/-17)
lib/lp/bugs/doc/checkwatches-cli-switches.txt (+14/-17)
lib/lp/bugs/doc/externalbugtracker-bug-imports.txt (+8/-10)
lib/lp/bugs/doc/externalbugtracker-bugzilla-api.txt (+13/-20)
lib/lp/bugs/doc/externalbugtracker-bugzilla-lp-plugin.txt (+15/-24)
lib/lp/bugs/doc/externalbugtracker-comment-pushing.txt (+26/-40)
lib/lp/bugs/doc/externalbugtracker-debbugs.txt (+8/-11)
lib/lp/bugs/doc/externalbugtracker-linking-back.txt (+3/-3)
lib/lp/bugs/doc/product-update-remote-product.txt (+38/-60)
lib/lp/bugs/mail/tests/test_handler.py (+2/-6)
lib/lp/bugs/model/tests/test_bugsummary.py (+2/-1)
lib/lp/bugs/model/tests/test_bugtask.py (+8/-6)
lib/lp/bugs/scripts/checkwatches/tests/test_core.py (+2/-2)
lib/lp/bugs/scripts/tests/test_bugnotification.py (+6/-3)
lib/lp/bugs/tests/bugs-emailinterface.txt (+8/-11)
lib/lp/bugs/tests/externalbugtracker.py (+18/-25)
lib/lp/bugs/tests/test_bugnotification.py (+2/-2)
lib/lp/bugs/tests/test_bugwatch.py (+2/-2)
lib/lp/bugs/tests/test_doc.py (+6/-5)
lib/lp/buildmaster/tests/test_buildmaster_documentation.py (+3/-2)
lib/lp/buildmaster/tests/test_manager.py (+6/-6)
lib/lp/code/mail/tests/test_codehandler.py (+43/-55)
lib/lp/code/model/tests/test_branch_privacy_triggers.py (+2/-1)
lib/lp/code/model/tests/test_branchjob.py (+19/-25)
lib/lp/code/model/tests/test_branchmergeproposaljobs.py (+15/-22)
lib/lp/code/model/tests/test_revisionauthor.py (+10/-10)
lib/lp/code/scripts/tests/test_revisionkarma.py (+4/-4)
lib/lp/code/tests/test_doc.py (+5/-4)
lib/lp/codehosting/scanner/tests/test_buglinks.py (+6/-7)
lib/lp/codehosting/scanner/tests/test_bzrsync.py (+36/-46)
lib/lp/codehosting/tests/test_branchdistro.py (+6/-8)
lib/lp/coop/answersbugs/tests/test_doc.py (+3/-2)
lib/lp/hardwaredb/doc/hwdb-device-tables.txt (+21/-21)
lib/lp/hardwaredb/scripts/tests/test_hwdb_submission_processing.py (+4/-6)
lib/lp/hardwaredb/tests/test_doc.py (+2/-1)
lib/lp/registry/browser/tests/test_person_view.py (+4/-3)
lib/lp/registry/doc/distribution-sourcepackage.txt (+3/-6)
lib/lp/registry/doc/karmacache.txt (+2/-2)
lib/lp/registry/doc/standing.txt (+3/-6)
lib/lp/registry/tests/test_distributionsourcepackage.py (+5/-7)
lib/lp/registry/tests/test_initderiveddistroseries.py (+6/-9)
lib/lp/registry/tests/test_pillarname_triggers.py (+2/-1)
lib/lp/registry/tests/test_prf_finder.py (+2/-2)
lib/lp/registry/tests/test_ro_user.py (+2/-1)
lib/lp/registry/tests/test_teammembership.py (+1/-1)
lib/lp/scripts/tests/test_garbo.py (+34/-35)
lib/lp/services/apachelogparser/tests/test_apachelogparser.py (+3/-2)
lib/lp/services/database/tests/test_transaction_decorators.py (+2/-1)
lib/lp/services/librarianserver/tests/test_db.py (+3/-2)
lib/lp/services/librarianserver/tests/test_gc.py (+8/-7)
lib/lp/services/librarianserver/tests/test_storage_db.py (+2/-1)
lib/lp/services/librarianserver/tests/test_web.py (+4/-6)
lib/lp/services/mail/doc/emailauthentication.txt (+3/-7)
lib/lp/services/mail/tests/incomingmail.txt (+5/-5)
lib/lp/services/mail/tests/test_doc.py (+2/-1)
lib/lp/services/mail/tests/test_incoming.py (+2/-1)
lib/lp/services/scripts/doc/script-monitoring.txt (+2/-2)
lib/lp/services/statistics/tests/test_update_stats.py (+2/-1)
lib/lp/services/worlddata/doc/language.txt (+4/-5)
lib/lp/soyuz/doc/buildd-scoring.txt (+15/-20)
lib/lp/soyuz/doc/closing-bugs-from-changelogs.txt (+10/-16)
lib/lp/soyuz/doc/distroarchseriesbinarypackage.txt (+4/-3)
lib/lp/soyuz/doc/package-arch-specific.txt (+33/-47)
lib/lp/soyuz/doc/package-cache.txt (+17/-30)
lib/lp/soyuz/doc/queuebuilder.txt (+3/-6)
lib/lp/soyuz/doc/soyuz-set-of-uploads.txt (+3/-3)
lib/lp/soyuz/scripts/tests/test_copypackage.py (+9/-14)
lib/lp/soyuz/scripts/tests/test_expire_archive_files.py (+5/-6)
lib/lp/soyuz/scripts/tests/test_publishdistro.py (+3/-2)
lib/lp/soyuz/scripts/tests/test_queue.py (+64/-96)
lib/lp/soyuz/tests/test_binarypackagebuildbehavior.py (+3/-2)
lib/lp/soyuz/tests/test_distroseriesbinarypackage.py (+8/-9)
lib/lp/soyuz/tests/test_distroseriesdifferencejob.py (+6/-10)
lib/lp/soyuz/tests/test_doc.py (+7/-6)
lib/lp/soyuz/tests/test_initializedistroseriesjob.py (+6/-5)
lib/lp/soyuz/tests/test_packagecopyjob.py (+11/-21)
lib/lp/soyuz/tests/test_packageupload.py (+3/-3)
lib/lp/soyuz/tests/test_processaccepted.py (+4/-6)
lib/lp/soyuz/tests/test_publishing.py (+5/-2)
lib/lp/testing/__init__.py (+2/-2)
lib/lp/testing/layers.py (+0/-7)
lib/lp/testing/tests/test_dbuser.py (+3/-3)
lib/lp/translations/doc/translationmessage-destroy.txt (+3/-3)
lib/lp/translations/doc/translationsoverview.txt (+4/-5)
lib/lp/translations/scripts/tests/test_migrate_current_flag.py (+4/-4)
lib/lp/translations/scripts/tests/test_remove_translations.py (+4/-3)
lib/lp/translations/scripts/tests/test_verify_pofile_stats.py (+4/-7)
lib/lp/translations/tests/test_translationbranchapprover.py (+2/-3)
lib/lp/translations/tests/test_translationbuildapprover.py (+2/-3)
lib/lp/translations/tests/test_translationimportqueue.py (+2/-2)
lib/lp/translations/tests/test_translationtemplatesbuild.py (+2/-3)
lib/lp/translations/tests/test_translationtemplatesbuildbehavior.py (+2/-7)
To merge this branch: bzr merge lp:~cjwatson/launchpad/kill-old-switchdbuser
Reviewer Review Type Date Requested Status
Benji York (community) code 2012-01-20 Approve on 2012-01-23
Review via email: mp+89459@code.launchpad.net

Commit Message

[r=benji][no-qa] Migrate everything to the functions in lp.testing.dbuser, and kill off the old LaunchpadZopelessLayer.switchDbUser method.

Description of the Change

LaunchpadZopelessLayer.switchDbUser has been sitting around marked DEPRECATED since September. Kill it off, replacing it with switch_dbuser, dbuser, or lp_dbuser, whichever seemed most appropriate. This way I stop having to think about the discrepancies while writing tests.

We can rely on switch_dbuser committing the transaction, saith wgrant, so I removed duplicate transaction.commit calls and similar immediately before switch_dbuser.

There's a fair amount of pre-existing lint, especially in doctests. I tried to make sure I wasn't introducing anything new, but this branch is already sufficiently large (let me know if you think it needs to be broken up) that I didn't want to bloat it even more.

To post a comment you must log in.
Benji York (benji) wrote :

This branch is a nice improvement. The typo and whitespace fixes are appreciated too.

review: Approve (code)

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'lib/lp/answers/tests/emailinterface.txt'
2--- lib/lp/answers/tests/emailinterface.txt 2011-12-29 05:29:36 +0000
3+++ lib/lp/answers/tests/emailinterface.txt 2012-01-24 12:44:15 +0000
4@@ -109,18 +109,15 @@
5 >>> foo_bar = personset.getByEmail('foo.bar@canonical.com')
6
7 >>> import transaction
8- >>> from lp.services.config import config
9- >>> from lp.testing.layers import LaunchpadZopelessLayer
10+ >>> from lp.testing.dbuser import lp_dbuser
11
12- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
13- >>> ubuntu = getUtility(IDistributionSet)['ubuntu']
14- >>> question = ubuntu.newQuestion(
15- ... no_priv, 'Unable to boot installer',
16- ... "I've tried installing Ubuntu on a Mac. But the installer never "
17- ... "boots.", datecreated=now.next())
18- >>> question_id = question.id
19- >>> transaction.commit()
20- >>> LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
21+ >>> with lp_dbuser():
22+ ... ubuntu = getUtility(IDistributionSet)['ubuntu']
23+ ... question = ubuntu.newQuestion(
24+ ... no_priv, 'Unable to boot installer',
25+ ... "I've tried installing Ubuntu on a Mac. But the installer "
26+ ... "never boots.", datecreated=now.next())
27+ ... question_id = question.id
28
29 # We need to refetch the question, since a new transaction was started.
30 >>> from lp.answers.interfaces.questioncollection import IQuestionSet
31@@ -371,17 +368,15 @@
32
33 Answers may also be linked to FAQ questions.
34
35- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
36-
37 >>> from zope.security.proxy import removeSecurityProxy
38- >>> login('foo.bar@canonical.com')
39- >>> faq = question.target.newFAQ(
40- ... no_priv, 'Why everyone think this is weird.',
41- ... "That's an easy one. It's because it is!")
42- >>> removeSecurityProxy(question).faq = faq
43- >>> transaction.commit()
44-
45- >>> LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
46+
47+ >>> with lp_dbuser():
48+ ... login('foo.bar@canonical.com')
49+ ... faq = question.target.newFAQ(
50+ ... no_priv, 'Why everyone think this is weird.',
51+ ... "That's an easy one. It's because it is!")
52+ ... removeSecurityProxy(question).faq = faq
53+
54 >>> login('no-priv@canonical.com')
55
56 # Make sure that the database security and permissions are set up
57
58=== modified file 'lib/lp/archivepublisher/tests/test_ftparchive.py'
59--- lib/lp/archivepublisher/tests/test_ftparchive.py 2012-01-01 02:58:52 +0000
60+++ lib/lp/archivepublisher/tests/test_ftparchive.py 2012-01-24 12:44:15 +0000
61@@ -30,6 +30,7 @@
62 DevNullLogger,
63 )
64 from lp.testing import TestCaseWithFactory
65+from lp.testing.dbuser import switch_dbuser
66 from lp.testing.layers import (
67 LaunchpadZopelessLayer,
68 ZopelessDatabaseLayer,
69@@ -71,7 +72,7 @@
70
71 def setUp(self):
72 super(TestFTPArchive, self).setUp()
73- self.layer.switchDbUser(config.archivepublisher.dbuser)
74+ switch_dbuser(config.archivepublisher.dbuser)
75
76 self._distribution = getUtility(IDistributionSet)['ubuntutest']
77 self._archive = self._distribution.main_archive
78
79=== modified file 'lib/lp/archivepublisher/tests/test_generate_ppa_htaccess.py'
80--- lib/lp/archivepublisher/tests/test_generate_ppa_htaccess.py 2012-01-01 02:58:52 +0000
81+++ lib/lp/archivepublisher/tests/test_generate_ppa_htaccess.py 2012-01-24 12:44:15 +0000
82@@ -34,6 +34,10 @@
83 ArchiveSubscriberStatus,
84 )
85 from lp.testing import TestCaseWithFactory
86+from lp.testing.dbuser import (
87+ lp_dbuser,
88+ switch_dbuser,
89+ )
90 from lp.testing.layers import LaunchpadZopelessLayer
91 from lp.testing.mail_helpers import pop_notifications
92
93@@ -63,8 +67,7 @@
94 script = HtaccessTokenGenerator("test tokens", test_args=test_args)
95 script.logger = BufferLogger()
96 script.txn = self.layer.txn
97- self.layer.txn.commit()
98- self.layer.switchDbUser(self.dbuser)
99+ switch_dbuser(self.dbuser)
100 return script
101
102 def runScript(self):
103@@ -272,10 +275,8 @@
104
105 # Now remove someone from team1, he will lose his token but
106 # everyone else keeps theirs.
107- self.layer.switchDbUser("launchpad")
108- team1_person.leave(team1)
109- self.layer.txn.commit()
110- self.layer.switchDbUser(self.dbuser)
111+ with lp_dbuser():
112+ team1_person.leave(team1)
113 # Clear out emails generated when leaving a team.
114 pop_notifications()
115
116@@ -293,11 +294,8 @@
117 # Promiscuous_person now leaves team1, but does not lose his
118 # token because he's also in team2. No other tokens are
119 # affected.
120- self.layer.txn.commit()
121- self.layer.switchDbUser("launchpad")
122- promiscuous_person.leave(team1)
123- self.layer.txn.commit()
124- self.layer.switchDbUser(self.dbuser)
125+ with lp_dbuser():
126+ promiscuous_person.leave(team1)
127 # Clear out emails generated when leaving a team.
128 pop_notifications()
129 script.deactivateTokens(send_email=True)
130@@ -312,15 +310,13 @@
131
132 # Team 2 now leaves parent_team, and all its members lose their
133 # tokens.
134- self.layer.switchDbUser("launchpad")
135- name12 = getUtility(IPersonSet).getByName("name12")
136- parent_team.setMembershipData(
137- team2, TeamMembershipStatus.APPROVED, name12)
138- parent_team.setMembershipData(
139- team2, TeamMembershipStatus.DEACTIVATED, name12)
140- self.assertFalse(team2.inTeam(parent_team))
141- self.layer.txn.commit()
142- self.layer.switchDbUser(self.dbuser)
143+ with lp_dbuser():
144+ name12 = getUtility(IPersonSet).getByName("name12")
145+ parent_team.setMembershipData(
146+ team2, TeamMembershipStatus.APPROVED, name12)
147+ parent_team.setMembershipData(
148+ team2, TeamMembershipStatus.DEACTIVATED, name12)
149+ self.assertFalse(team2.inTeam(parent_team))
150 script.deactivateTokens()
151 for person in persons2:
152 self.assertDeactivated(tokens[person])
153@@ -547,7 +543,7 @@
154 # This happens even if they have no tokens.
155
156 # Create a public PPA that should not be in the list.
157- public_ppa = self.factory.makeArchive(private=False)
158+ self.factory.makeArchive(private=False)
159
160 script = self.getScript()
161 self.assertContentEqual([self.ppa], script.getNewPrivatePPAs())
162@@ -570,7 +566,6 @@
163
164 def test_getNewTokensSinceLastRun_no_previous_run(self):
165 """All valid tokens returned if there is no record of previous run."""
166- now = datetime.now(pytz.UTC)
167 tokens = self.setupDummyTokens()[1]
168
169 # If there is no record of the script running previously, all
170@@ -587,7 +582,7 @@
171
172 getUtility(IScriptActivitySet).recordSuccess(
173 'generate-ppa-htaccess', date_started=script_start_time,
174- date_completed = script_end_time)
175+ date_completed=script_end_time)
176 tokens = self.setupDummyTokens()[1]
177 # This token will not be included.
178 removeSecurityProxy(tokens[0]).date_created = before_previous_start
179@@ -632,7 +627,6 @@
180
181 def test_getNewTokensSinceLastRun_only_active_tokens(self):
182 """Only active tokens are returned."""
183- now = datetime.now(pytz.UTC)
184 tokens = self.setupDummyTokens()[1]
185 tokens[0].deactivate()
186
187
188=== modified file 'lib/lp/archivepublisher/tests/test_publisher_documentation.py'
189--- lib/lp/archivepublisher/tests/test_publisher_documentation.py 2011-12-29 05:29:36 +0000
190+++ lib/lp/archivepublisher/tests/test_publisher_documentation.py 2012-01-24 12:44:15 +0000
191@@ -10,6 +10,7 @@
192 import unittest
193
194 from lp.services.config import config
195+from lp.testing.dbuser import switch_dbuser
196 from lp.testing.layers import LaunchpadZopelessLayer
197 from lp.testing.systemdocs import (
198 LayeredDocFileSuite,
199@@ -20,7 +21,7 @@
200
201 def archivePublisherSetUp(test):
202 setUp(test)
203- LaunchpadZopelessLayer.switchDbUser(config.archivepublisher.dbuser)
204+ switch_dbuser(config.archivepublisher.dbuser)
205
206
207 def test_suite():
208
209=== modified file 'lib/lp/archiveuploader/tests/nascentupload-announcements.txt'
210--- lib/lp/archiveuploader/tests/nascentupload-announcements.txt 2011-12-28 17:03:06 +0000
211+++ lib/lp/archiveuploader/tests/nascentupload-announcements.txt 2012-01-24 12:44:15 +0000
212@@ -33,8 +33,8 @@
213
214 We need to be logged into the security model in order to get any further
215
216- >>> from lp.testing.layers import LaunchpadZopelessLayer
217- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
218+ >>> from lp.testing.dbuser import switch_dbuser
219+ >>> switch_dbuser('launchpad')
220 >>> login('foo.bar@canonical.com')
221
222 Helper functions to examine emails that were sent:
223
224=== modified file 'lib/lp/archiveuploader/tests/nascentupload-closing-bugs.txt'
225--- lib/lp/archiveuploader/tests/nascentupload-closing-bugs.txt 2011-12-30 06:14:56 +0000
226+++ lib/lp/archiveuploader/tests/nascentupload-closing-bugs.txt 2012-01-24 12:44:15 +0000
227@@ -25,20 +25,17 @@
228 >>> bar_src.queue_root.setAccepted()
229 >>> pub_records = bar_src.queue_root.realiseUpload()
230
231- >>> from lp.services.database.sqlbase import commit
232- >>> commit()
233-
234 Check the current status of the bug we are supposed to fix:
235
236 >>> the_bug_id = 6
237
238- >>> from lp.testing.layers import LaunchpadZopelessLayer
239+ >>> from lp.testing.dbuser import switch_dbuser
240 >>> from lp.bugs.interfaces.bug import IBugSet
241 >>> from lp.bugs.interfaces.bugtask import IBugTaskSet
242 >>> from lp.registry.interfaces.distribution import IDistributionSet
243 >>> from lp.registry.interfaces.person import IPersonSet
244 >>> login('no-priv@canonical.com')
245- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
246+ >>> switch_dbuser('launchpad')
247
248 >>> bugtask_owner = getUtility(IPersonSet).getByName('kinnison')
249 >>> ubuntu = getUtility(IDistributionSet)['ubuntu']
250@@ -60,9 +57,8 @@
251
252 Return to the original test environment:
253
254- >>> commit()
255 >>> from lp.services.config import config
256- >>> LaunchpadZopelessLayer.switchDbUser(config.uploader.dbuser)
257+ >>> switch_dbuser(config.uploader.dbuser)
258 >>> login('foo.bar@canonical.com')
259
260
261
262=== modified file 'lib/lp/archiveuploader/tests/nascentupload-ddebs.txt'
263--- lib/lp/archiveuploader/tests/nascentupload-ddebs.txt 2011-12-29 05:29:36 +0000
264+++ lib/lp/archiveuploader/tests/nascentupload-ddebs.txt 2012-01-24 12:44:15 +0000
265@@ -10,8 +10,9 @@
266 for obtaining extra information about crashes in the corresponding
267 feature.
268
269+ >>> import transaction
270 >>> from lp.services.config import config
271- >>> from lp.testing.layers import LaunchpadZopelessLayer
272+ >>> from lp.testing.dbuser import switch_dbuser
273
274 >>> from lp.soyuz.tests.test_publishing import (
275 ... SoyuzTestPublisher)
276@@ -34,7 +35,7 @@
277 >>> result = src.do_accept()
278 >>> print src.queue_root.status.name
279 NEW
280- >>> LaunchpadZopelessLayer.txn.commit()
281+ >>> transaction.commit()
282
283 We don't really care where the source ends up, so we just accept the
284 default overrides. It is now pending publication.
285@@ -86,8 +87,7 @@
286 >>> universe = getUtility(IComponentSet)['universe']
287 >>> devel = getUtility(ISectionSet)['devel']
288
289- >>> LaunchpadZopelessLayer.txn.commit()
290- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
291+ >>> switch_dbuser('launchpad')
292
293 >>> bin.queue_root.overrideBinaries(main, devel, None, [main, universe])
294 True
295@@ -96,13 +96,11 @@
296 >>> print bin.queue_root.status.name
297 ACCEPTED
298
299- >>> LaunchpadZopelessLayer.txn.commit()
300- >>> LaunchpadZopelessLayer.switchDbUser(config.uploadqueue.dbuser)
301+ >>> switch_dbuser(config.uploadqueue.dbuser)
302
303 >>> bin_pubs = bin.queue_root.realiseUpload()
304
305- >>> LaunchpadZopelessLayer.txn.commit()
306- >>> LaunchpadZopelessLayer.switchDbUser('uploader')
307+ >>> switch_dbuser('uploader')
308
309 Now, both, binary and debug-symbol packages are pending publication.
310
311@@ -155,8 +153,7 @@
312 ... owner=ubuntu.owner, purpose=ArchivePurpose.COPY,
313 ... name='test-rebuild')
314
315- >>> LaunchpadZopelessLayer.txn.commit()
316- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
317+ >>> switch_dbuser('launchpad')
318
319 >>> initial_source = test_publisher.getPubSource(
320 ... sourcename='debug', version='0.9', archive=copy)
321@@ -184,13 +181,11 @@
322 When published, DDEB ends up in the same archive as the DEB, unlike
323 the ones in the primary archive.
324
325- >>> LaunchpadZopelessLayer.txn.commit()
326- >>> LaunchpadZopelessLayer.switchDbUser(config.uploadqueue.dbuser)
327+ >>> switch_dbuser(config.uploadqueue.dbuser)
328
329 >>> bin_pubs = bin.queue_root.realiseUpload()
330
331- >>> LaunchpadZopelessLayer.txn.commit()
332- >>> LaunchpadZopelessLayer.switchDbUser('uploader')
333+ >>> switch_dbuser('uploader')
334
335 >>> for bin_pub in bin_pubs:
336 ... print '%s %s %s %s %s' % (
337@@ -216,4 +211,4 @@
338 >>> print bin.rejection_message
339 Duplicated debug packages: debug-bin-dbgsym 1.0-1 (i386)
340 Orphaned debug packages: not-debug-bin-dbgsym 1.0-1 (i386)
341-
342+
343
344=== modified file 'lib/lp/archiveuploader/tests/nascentupload-packageset.txt'
345--- lib/lp/archiveuploader/tests/nascentupload-packageset.txt 2011-12-30 06:14:56 +0000
346+++ lib/lp/archiveuploader/tests/nascentupload-packageset.txt 2012-01-24 12:44:15 +0000
347@@ -1,33 +1,31 @@
348 In order to prepare the tests below some initialization is required.
349
350+ >>> import transaction
351 >>> from lp.archiveuploader.nascentupload import NascentUpload
352 >>> from lp.archiveuploader.tests import datadir, getPolicy
353- >>> from lp.services.database.sqlbase import commit
354- >>> from lp.testing.layers import LaunchpadZopelessLayer
355 >>> from lp.registry.interfaces.person import IPersonSet
356 >>> from lp.registry.interfaces.sourcepackagename import ISourcePackageNameSet
357 >>> from lp.soyuz.enums import ArchivePermissionType
358 >>> from lp.soyuz.interfaces.archivepermission import IArchivePermissionSet
359 >>> from lp.soyuz.interfaces.packageset import IPackagesetSet
360+ >>> from lp.testing.dbuser import switch_dbuser
361
362 >>> insecure_policy = getPolicy(
363 ... name='insecure', distro='ubuntu', distroseries='hoary')
364 >>> ap_set = getUtility(IArchivePermissionSet)
365 >>> name16 = getUtility(IPersonSet).getByName('name16')
366 >>> bar_name = getUtility(ISourcePackageNameSet).getOrCreateByName("bar")
367- >>> commit()
368
369 Let's modify the current ACL rules for ubuntu, moving the upload
370 rights to all components from 'ubuntu-team' to 'mark':
371
372- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
373+ >>> switch_dbuser('launchpad')
374 >>> from lp.soyuz.model.archivepermission import ArchivePermission
375 >>> new_uploader = getUtility(IPersonSet).getByName('mark')
376 >>> for permission in ArchivePermission.select():
377 ... permission.person = new_uploader
378 ... permission.syncUpdate()
379- >>> commit()
380- >>> LaunchpadZopelessLayer.switchDbUser('uploader')
381+ >>> switch_dbuser('uploader')
382
383 This time the upload will fail because the ACLs don't let
384 "name16", the key owner, upload a package.
385@@ -48,8 +46,6 @@
386 We can grant selective, package set based upload permissions to the user
387 in order to facilitate uploads.
388
389- >>> commit()
390- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
391 >>> import operator
392 >>> def print_permission(result_set):
393 ... for perm in result_set.order_by(
394@@ -84,8 +80,7 @@
395 Let's first add an empty package set, grant 'name16' an archive permission
396 to it and see whether that changes things.
397
398- >>> commit()
399- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
400+ >>> switch_dbuser('launchpad')
401
402 >>> def sort_by_id(iterable):
403 ... return sorted(iterable, key=operator.attrgetter('id'))
404@@ -98,7 +93,7 @@
405 >>> ps_set = getUtility(IPackagesetSet)
406 >>> empty_ps = ps_set.new(
407 ... u'empty-pkg-set', u'Empty package set.', name16)
408- >>> commit()
409+ >>> transaction.commit()
410
411 And here's name16's upload permission for it.
412
413@@ -133,7 +128,7 @@
414
415 >>> foo_ps = ps_set.new(
416 ... u'foo-pkg-set', u'Packages that require special care.', name16)
417- >>> commit()
418+ >>> transaction.commit()
419
420 Add 'bar' to the 'foo' package set.
421
422@@ -166,8 +161,7 @@
423
424 With the authorization above the upload should work again.
425
426- >>> commit()
427- >>> LaunchpadZopelessLayer.switchDbUser('uploader')
428+ >>> switch_dbuser('uploader')
429 >>> bar2 = NascentUpload.from_changesfile_path(
430 ... datadir('suite/bar_1.0-1/bar_1.0-1_source.changes'),
431 ... insecure_policy, DevNullLogger())
432
433=== modified file 'lib/lp/archiveuploader/tests/nascentupload.txt'
434--- lib/lp/archiveuploader/tests/nascentupload.txt 2011-12-30 06:14:56 +0000
435+++ lib/lp/archiveuploader/tests/nascentupload.txt 2012-01-24 12:44:15 +0000
436@@ -638,12 +638,9 @@
437 to set hoary to CURRENT in order to do this because we're not allowed
438 to upload to -UPDATES in a DEVELOPMENT series.
439
440- >>> from lp.testing.layers import LaunchpadZopelessLayer
441- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
442- >>> from lp.services.database.sqlbase import commit
443- >>> hoary.status = SeriesStatus.CURRENT
444- >>> commit()
445- >>> LaunchpadZopelessLayer.switchDbUser('uploader')
446+ >>> from lp.testing.dbuser import lp_dbuser
447+ >>> with lp_dbuser():
448+ ... hoary.status = SeriesStatus.CURRENT
449
450 Note that the policy do not have fixed distroseries, it will be
451 overridden by the changesfile:
452@@ -672,10 +669,8 @@
453
454 And pop it back to development now that we're done
455
456- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
457- >>> hoary.status = SeriesStatus.DEVELOPMENT
458- >>> commit()
459- >>> LaunchpadZopelessLayer.switchDbUser('uploader')
460+ >>> with lp_dbuser():
461+ ... hoary.status = SeriesStatus.DEVELOPMENT
462
463 Check the uploader behaviour against a missing orig.tar.gz file,
464 bug # 30741.
465@@ -785,15 +780,12 @@
466 Let's modify the current ACL rules for ubuntu, moving the upload
467 rights to all components from 'ubuntu-team' to 'mark':
468
469- >>> commit()
470- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
471 >>> from lp.soyuz.model.archivepermission import ArchivePermission
472- >>> new_uploader = getUtility(IPersonSet).getByName('mark')
473- >>> for permission in ArchivePermission.select():
474- ... permission.person = new_uploader
475- ... permission.syncUpdate()
476- >>> commit()
477- >>> LaunchpadZopelessLayer.switchDbUser('uploader')
478+ >>> with lp_dbuser():
479+ ... new_uploader = getUtility(IPersonSet).getByName('mark')
480+ ... for permission in ArchivePermission.select():
481+ ... permission.person = new_uploader
482+ ... permission.syncUpdate()
483
484 This time the upload will fail because the ACLs don't let
485 "name16", the key owner, upload a package.
486@@ -830,18 +822,16 @@
487 he currently has no upload rights at all to Ubuntu. However, we can add
488 an ArchivePermission record to permit him to upload "bar" specifically.
489
490- >>> commit()
491- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
492 >>> from lp.registry.interfaces.sourcepackagename import (
493 ... ISourcePackageNameSet)
494 >>> from lp.soyuz.enums import ArchivePermissionType
495- >>> bar_name = getUtility(ISourcePackageNameSet).getOrCreateByName("bar")
496- >>> discard = ArchivePermission(
497- ... archive=ubuntu.main_archive, person=name16,
498- ... permission=ArchivePermissionType.UPLOAD,
499- ... sourcepackagename=bar_name, component=None)
500- >>> commit()
501- >>> LaunchpadZopelessLayer.switchDbUser('uploader')
502+ >>> with lp_dbuser():
503+ ... bar_name = getUtility(ISourcePackageNameSet).getOrCreateByName(
504+ ... "bar")
505+ ... discard = ArchivePermission(
506+ ... archive=ubuntu.main_archive, person=name16,
507+ ... permission=ArchivePermissionType.UPLOAD,
508+ ... sourcepackagename=bar_name, component=None)
509
510 Now try the "bar" upload:
511
512
513=== modified file 'lib/lp/archiveuploader/tests/test_nascentupload_documentation.py'
514--- lib/lp/archiveuploader/tests/test_nascentupload_documentation.py 2012-01-01 02:58:52 +0000
515+++ lib/lp/archiveuploader/tests/test_nascentupload_documentation.py 2012-01-24 12:44:15 +0000
516@@ -25,6 +25,7 @@
517 login,
518 logout,
519 )
520+from lp.testing.dbuser import switch_dbuser
521 from lp.testing.gpgkeys import import_public_test_keys
522 from lp.testing.layers import LaunchpadZopelessLayer
523 from lp.testing.systemdocs import (
524@@ -99,7 +100,7 @@
525 login('foo.bar@canonical.com')
526 testGlobalsSetup(test)
527 prepareHoaryForUploads(test)
528- LaunchpadZopelessLayer.switchDbUser('uploader')
529+ switch_dbuser('uploader')
530
531
532 def tearDown(test):
533
534=== modified file 'lib/lp/archiveuploader/tests/test_ppauploadprocessor.py'
535--- lib/lp/archiveuploader/tests/test_ppauploadprocessor.py 2011-12-30 06:14:56 +0000
536+++ lib/lp/archiveuploader/tests/test_ppauploadprocessor.py 2012-01-24 12:44:15 +0000
537@@ -43,6 +43,7 @@
538 from lp.soyuz.model.publishing import BinaryPackagePublishingHistory
539 from lp.soyuz.tests.fakepackager import FakePackager
540 from lp.soyuz.tests.test_publishing import SoyuzTestPublisher
541+from lp.testing.dbuser import switch_dbuser
542
543
544 class TestPPAUploadProcessorBase(TestUploadProcessorBase):
545@@ -802,7 +803,6 @@
546 self.switchToAdmin()
547 self.breezy['i386'].supports_virtualized = False
548 self.switchToUploader()
549- self.layer.commit()
550
551 # Next version can't be accepted because it can't be built.
552 packager.buildVersion('1.0-2', suite=self.breezy.name, arch="i386")
553@@ -1126,7 +1126,6 @@
554 bar_src.requestDeletion(self.name16)
555 bar_src.dateremoved = UTC_NOW
556 self.switchToUploader()
557- self.layer.txn.commit()
558
559 # bar_1.0-3 contains an orig file of the same version with
560 # different contents than the one we previously uploaded.
561@@ -1196,7 +1195,7 @@
562 the given size in bytes.
563
564 Uses `SoyuzTestPublisher` class to create the corresponding publishing
565- record, then switchDbUser as 'librariangc' and update the size of the
566+ record, then switch_dbuser as 'librariangc' and update the size of the
567 source file to the given value.
568 """
569 self.switchToAdmin()
570@@ -1207,18 +1206,16 @@
571 status=PackagePublishingStatus.PUBLISHED)
572 alias_id = pub_src.sourcepackagerelease.files[0].libraryfile.id
573
574- self.layer.commit()
575- self.layer.switchDbUser('librariangc')
576+ switch_dbuser('librariangc')
577 content = getUtility(ILibraryFileAliasSet)[alias_id].content
578 content = removeSecurityProxy(content)
579 # Decrement the archive index parcel automatically added by
580 # IArchive.estimated_size.
581 content.filesize = size - 1024
582- self.layer.commit()
583 self.switchToUploader()
584
585 # Re-initialize uploadprocessor since it depends on the new
586- # transaction reset by switchDbUser.
587+ # transaction reset by switch_dbuser.
588 self.uploadprocessor = self.getUploadProcessor(self.layer.txn)
589
590 def testPPASizeQuotaSourceRejection(self):
591
592=== modified file 'lib/lp/archiveuploader/tests/test_uploadprocessor.py'
593--- lib/lp/archiveuploader/tests/test_uploadprocessor.py 2012-01-11 08:52:22 +0000
594+++ lib/lp/archiveuploader/tests/test_uploadprocessor.py 2012-01-24 12:44:15 +0000
595@@ -17,7 +17,6 @@
596
597 from fixtures import MonkeyPatch
598 from storm.locals import Store
599-import transaction
600 from zope.component import (
601 getGlobalSiteManager,
602 getUtility,
603@@ -101,6 +100,7 @@
604 TestCase,
605 TestCaseWithFactory,
606 )
607+from lp.testing.dbuser import switch_dbuser
608 from lp.testing.fakemethod import FakeMethod
609 from lp.testing.gpgkeys import import_public_test_keys
610 from lp.testing.layers import LaunchpadZopelessLayer
611@@ -132,12 +132,10 @@
612 layer = LaunchpadZopelessLayer
613
614 def switchToUploader(self):
615- transaction.commit()
616- self.layer.switchDbUser("uploader")
617+ switch_dbuser("uploader")
618
619 def switchToAdmin(self):
620- transaction.commit()
621- self.layer.switchDbUser("launchpad_main")
622+ switch_dbuser("launchpad_main")
623
624 def setUp(self):
625 super(TestUploadProcessorBase, self).setUp()
626
627=== modified file 'lib/lp/bugs/doc/bug-private-by-default.txt'
628--- lib/lp/bugs/doc/bug-private-by-default.txt 2011-12-28 17:03:06 +0000
629+++ lib/lp/bugs/doc/bug-private-by-default.txt 2012-01-24 12:44:15 +0000
630@@ -4,11 +4,12 @@
631 A product with private bugs by default must always have a bug supervisor
632 (this is enforced by a DB constraint).
633
634- >>> from lp.testing.layers import LaunchpadZopelessLayer
635 >>> from lp.bugs.interfaces.bug import CreateBugParams
636 >>> from lp.registry.interfaces.person import IPersonSet
637 >>> from lp.registry.interfaces.product import IProductSet
638- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
639+ >>> from lp.testing.dbuser import switch_dbuser
640+
641+ >>> switch_dbuser('launchpad')
642 >>> no_priv = getUtility(IPersonSet).getByName('no-priv')
643 >>> name16 = getUtility(IPersonSet).get(16)
644 >>> landscape = getUtility(IProductSet).getByName('landscape')
645
646=== modified file 'lib/lp/bugs/doc/bug-watch-activity.txt'
647--- lib/lp/bugs/doc/bug-watch-activity.txt 2011-12-29 05:29:36 +0000
648+++ lib/lp/bugs/doc/bug-watch-activity.txt 2012-01-24 12:44:15 +0000
649@@ -7,9 +7,8 @@
650 We can create a new BugWatchActivity record for a bug watch using that
651 BugWatch's addActivity() method.
652
653- >>> from lp.services.config import config
654 >>> from lp.services.database.lpstorm import IStore
655- >>> from lp.testing.layers import LaunchpadZopelessLayer
656+ >>> from lp.testing.dbuser import lp_dbuser
657 >>> from lp.bugs.model.bugwatch import BugWatchActivity
658
659 In order to create a BugWatch to test with we need to switch DB users.
660@@ -17,13 +16,8 @@
661 at the same time _only_ the checkwatches DB user can create
662 BugWatchActivity instances.
663
664- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
665- >>> bug_watch = factory.makeBugWatch(remote_bug='42')
666-
667- >>> # This commit is unavoidable, otherwise we lose the watch when we
668- >>> # switch users.
669- >>> transaction.commit()
670- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
671+ >>> with lp_dbuser():
672+ ... bug_watch = factory.makeBugWatch(remote_bug='42')
673
674 When a BugWatch is first created there has been no activity on it.
675
676
677=== modified file 'lib/lp/bugs/doc/bugnotification-sending.txt'
678--- lib/lp/bugs/doc/bugnotification-sending.txt 2011-12-30 06:14:56 +0000
679+++ lib/lp/bugs/doc/bugnotification-sending.txt 2012-01-24 12:44:15 +0000
680@@ -349,22 +349,7 @@
681 Duplicates
682 ----------
683
684-We will need some helper functions.
685-
686- >>> from lp.services.config import config
687- >>> from lp.services.database.sqlbase import commit
688- >>> from lp.testing.layers import LaunchpadZopelessLayer
689-
690- >>> def switch_db_to_launchpad():
691- ... commit()
692- ... LaunchpadZopelessLayer.switchDbUser('launchpad')
693-
694- >>> def switch_db_to_bugnotification():
695- ... commit()
696- ... LaunchpadZopelessLayer.switchDbUser(
697- ... config.malone.bugnotification_dbuser)
698-
699-We will also need a fresh new bug.
700+We will need a fresh new bug.
701
702 >>> from lp.bugs.interfaces.bug import CreateBugParams
703 >>> from lp.registry.interfaces.distribution import IDistributionSet
704
705=== modified file 'lib/lp/bugs/doc/bugtracker-person.txt'
706--- lib/lp/bugs/doc/bugtracker-person.txt 2011-12-30 06:14:56 +0000
707+++ lib/lp/bugs/doc/bugtracker-person.txt 2012-01-24 12:44:15 +0000
708@@ -19,14 +19,10 @@
709 We'll rename the bugtracker to make the tests more readable.
710
711 >>> from lp.services.database.sqlbase import commit
712- >>> from lp.testing.layers import LaunchpadZopelessLayer
713- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
714-
715- >>> bugtracker.name = 'bugzilla-checkwatches'
716- >>> commit()
717-
718- >>> from lp.services.config import config
719- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
720+ >>> from lp.testing.dbuser import lp_dbuser
721+
722+ >>> with lp_dbuser():
723+ ... bugtracker.name = 'bugzilla-checkwatches'
724
725 >>> bugtracker_person = bugtracker.linkPersonToSelf(
726 ... 'some-name-i-made-up', sample_person)
727@@ -161,15 +157,9 @@
728
729 >>> other_bug_tracker = new_bugtracker(BugTrackerType.BUGZILLA)
730
731- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
732-
733- >>> bugtracker.name = 'bugzilla-checkwatches-renamed'
734- >>> commit()
735-
736- >>> other_bug_tracker.name = 'bugzilla-checkwatches'
737- >>> commit()
738-
739- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
740+ >>> with lp_dbuser():
741+ ... bugtracker.name = 'bugzilla-checkwatches-renamed'
742+ ... other_bug_tracker.name = 'bugzilla-checkwatches'
743
744 A new Person has been created for 'noemail' on other_bug_tracker, even
745 though that bug tracker's name is the same as one from which we've
746
747=== modified file 'lib/lp/bugs/doc/checkwatches-cli-switches.txt'
748--- lib/lp/bugs/doc/checkwatches-cli-switches.txt 2011-12-30 06:14:56 +0000
749+++ lib/lp/bugs/doc/checkwatches-cli-switches.txt 2012-01-24 12:44:15 +0000
750@@ -27,16 +27,13 @@
751
752 If a bug tracker is disabled checkwatches won't try to update it.
753
754- >>> from lp.services.config import config
755- >>> from lp.testing.layers import LaunchpadZopelessLayer
756+ >>> from lp.testing.dbuser import lp_dbuser
757
758- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
759- >>> login('foo.bar@canonical.com')
760- >>> bug_tracker = factory.makeBugTracker('http://example.com')
761- >>> bug_tracker.active = False
762- >>> bug_tracker_name = bug_tracker.name
763- >>> transaction.commit()
764- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
765+ >>> with lp_dbuser():
766+ ... login('foo.bar@canonical.com')
767+ ... bug_tracker = factory.makeBugTracker('http://example.com')
768+ ... bug_tracker.active = False
769+ ... bug_tracker_name = bug_tracker.name
770
771 >>> updater.updateBugTrackers([bug_tracker_name])
772 DEBUG...Updates are disabled for bug tracker at http://example.com
773@@ -46,6 +43,8 @@
774 line.
775
776 >>> from lp.bugs.scripts.checkwatches import CheckWatchesCronScript
777+ >>> from lp.services.config import config
778+
779 >>> class TestCheckWatchesCronScript(CheckWatchesCronScript):
780 ...
781 ... def __init__(self, name, dbuser=None, test_args=None):
782@@ -93,14 +92,12 @@
783 >>> from lp.testing.factory import LaunchpadObjectFactory
784
785 >>> factory = LaunchpadObjectFactory()
786- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
787- >>> login('foo.bar@canonical.com')
788- >>> savannah = getUtility(IBugTrackerSet).getByName('savannah')
789- >>> for i in range(5):
790- ... bug_watch = factory.makeBugWatch(bugtracker=savannah)
791- ... bug_watch.lastchecked = datetime.now(pytz.timezone('UTC'))
792- >>> transaction.commit()
793- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
794+ >>> with lp_dbuser():
795+ ... login('foo.bar@canonical.com')
796+ ... savannah = getUtility(IBugTrackerSet).getByName('savannah')
797+ ... for i in range(5):
798+ ... bug_watch = factory.makeBugWatch(bugtracker=savannah)
799+ ... bug_watch.lastchecked = datetime.now(pytz.timezone('UTC'))
800
801 >>> run_cronscript_with_args(['-vvt', 'savannah', '--reset'])
802 DEBUG Enabled by DEFAULT section
803
804=== modified file 'lib/lp/bugs/doc/externalbugtracker-bug-imports.txt'
805--- lib/lp/bugs/doc/externalbugtracker-bug-imports.txt 2011-12-29 05:29:36 +0000
806+++ lib/lp/bugs/doc/externalbugtracker-bug-imports.txt 2012-01-24 12:44:15 +0000
807@@ -47,17 +47,15 @@
808 distributions are supported as the bug target.
809
810 # Make sane data to play this test.
811- >>> from lp.services.config import config
812+ >>> from lp.testing.dbuser import lp_dbuser
813 >>> from lp.testing.layers import LaunchpadZopelessLayer
814- >>> transaction.commit()
815- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
816- >>> debian = getUtility(IDistributionSet).getByName('debian')
817- >>> evolution_dsp = debian.getSourcePackage('evolution')
818- >>> ignore = factory.makeSourcePackagePublishingHistory(
819- ... distroseries=debian.currentseries,
820- ... sourcepackagename=evolution_dsp.sourcepackagename)
821- >>> transaction.commit()
822- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
823+
824+ >>> with lp_dbuser():
825+ ... debian = getUtility(IDistributionSet).getByName('debian')
826+ ... evolution_dsp = debian.getSourcePackage('evolution')
827+ ... ignore = factory.makeSourcePackagePublishingHistory(
828+ ... distroseries=debian.currentseries,
829+ ... sourcepackagename=evolution_dsp.sourcepackagename)
830
831 >>> from lp.bugs.scripts.checkwatches import CheckwatchesMaster
832 >>> debian = getUtility(IDistributionSet).getByName('debian')
833
834=== modified file 'lib/lp/bugs/doc/externalbugtracker-bugzilla-api.txt'
835--- lib/lp/bugs/doc/externalbugtracker-bugzilla-api.txt 2011-12-30 06:14:56 +0000
836+++ lib/lp/bugs/doc/externalbugtracker-bugzilla-api.txt 2012-01-24 12:44:15 +0000
837@@ -382,7 +382,7 @@
838 Importing remote comments
839 -------------------------
840
841-BugzillaAPI implments the ISupportsCommentImport interface, which
842+BugzillaAPI implements the ISupportsCommentImport interface, which
843 means that we can use it to import comments from the remote Bugzilla
844 instance.
845
846@@ -395,9 +395,7 @@
847 To test the comment importing methods we need to add an example bug,
848 bugtracker and a couple of bugwatches.
849
850- >>> from lp.services.config import config
851- >>> from lp.services.database.sqlbase import commit
852- >>> from lp.testing.layers import LaunchpadZopelessLayer
853+ >>> from lp.testing.dbuser import lp_dbuser
854
855 >>> from lp.bugs.interfaces.bug import CreateBugParams
856 >>> from lp.bugs.interfaces.bugtracker import BugTrackerType
857@@ -408,22 +406,17 @@
858
859 >>> bug_tracker = new_bugtracker(BugTrackerType.BUGZILLA)
860
861- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
862-
863- >>> sample_person = getUtility(IPersonSet).getByEmail(
864- ... 'test@canonical.com')
865- >>> firefox = getUtility(IProductSet).getByName('firefox')
866- >>> bug = firefox.createBug(
867- ... CreateBugParams(sample_person, "Yet another test bug",
868- ... "Yet another test description.",
869- ... subscribe_owner=False))
870-
871- >>> bug_watch = bug.addWatch(bug_tracker, '1', sample_person)
872- >>> bug_watch_two = bug.addWatch(bug_tracker, '2', sample_person)
873- >>> bug_watch_broken = bug.addWatch(bug_tracker, '42', sample_person)
874- >>> commit()
875-
876- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
877+ >>> with lp_dbuser():
878+ ... sample_person = getUtility(IPersonSet).getByEmail(
879+ ... 'test@canonical.com')
880+ ... firefox = getUtility(IProductSet).getByName('firefox')
881+ ... bug = firefox.createBug(
882+ ... CreateBugParams(sample_person, "Yet another test bug",
883+ ... "Yet another test description.",
884+ ... subscribe_owner=False))
885+ ... bug_watch = bug.addWatch(bug_tracker, '1', sample_person)
886+ ... bug_watch_two = bug.addWatch(bug_tracker, '2', sample_person)
887+ ... bug_watch_broken = bug.addWatch(bug_tracker, '42', sample_person)
888
889
890 getCommentIds()
891
892=== modified file 'lib/lp/bugs/doc/externalbugtracker-bugzilla-lp-plugin.txt'
893--- lib/lp/bugs/doc/externalbugtracker-bugzilla-lp-plugin.txt 2011-12-30 06:14:56 +0000
894+++ lib/lp/bugs/doc/externalbugtracker-bugzilla-lp-plugin.txt 2012-01-24 12:44:15 +0000
895@@ -55,17 +55,14 @@
896 _handleLoginToken() method of TestBugzillaXMLRPCTransport so that it can
897 work with the right database user.
898
899- >>> from lp.services.config import config
900- >>> from lp.testing.layers import LaunchpadZopelessLayer
901 >>> from lp.bugs.tests.externalbugtracker import (
902 ... TestInternalXMLRPCTransport)
903+ >>> from lp.testing.dbuser import lp_dbuser
904
905 >>> class ZopelessBugzillaXMLRPCTransport(TestBugzillaXMLRPCTransport):
906 ... def _handleLoginToken(self, token_text):
907- ... LaunchpadZopelessLayer.switchDbUser('launchpad')
908- ... self._consumeLoginToken(token_text)
909- ... LaunchpadZopelessLayer.switchDbUser(
910- ... config.checkwatches.dbuser)
911+ ... with lp_dbuser():
912+ ... self._consumeLoginToken(token_text)
913
914 >>> test_transport = ZopelessBugzillaXMLRPCTransport(
915 ... 'http://example.com/')
916@@ -315,7 +312,7 @@
917 -----------------------
918
919 BugzillaLPPlugin doesn't have any special functionality for getting
920-remote statuses. See the "Getting remote statuses" section of
921+remote statuses. See the "Getting remote statuses" section of
922 externalbugtracker-bugzilla-api.txt for details of getting remote
923 statuses from Bugzilla APIs.
924
925@@ -342,7 +339,6 @@
926 To test the comment importing methods we need to add an example bug,
927 bugtracker and a couple of bugwatches.
928
929- >>> from lp.services.database.sqlbase import commit
930 >>> from lp.bugs.interfaces.bug import CreateBugParams
931 >>> from lp.bugs.interfaces.bugtracker import BugTrackerType
932 >>> from lp.registry.interfaces.person import IPersonSet
933@@ -352,22 +348,17 @@
934
935 >>> bug_tracker = new_bugtracker(BugTrackerType.BUGZILLA)
936
937- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
938-
939- >>> sample_person = getUtility(IPersonSet).getByEmail(
940- ... 'test@canonical.com')
941- >>> firefox = getUtility(IProductSet).getByName('firefox')
942- >>> bug = firefox.createBug(
943- ... CreateBugParams(sample_person, "Yet another test bug",
944- ... "Yet another test description.",
945- ... subscribe_owner=False))
946-
947- >>> bug_watch = bug.addWatch(bug_tracker, '1', sample_person)
948- >>> bug_watch_two = bug.addWatch(bug_tracker, '2', sample_person)
949- >>> bug_watch_broken = bug.addWatch(bug_tracker, '42', sample_person)
950- >>> commit()
951-
952- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
953+ >>> with lp_dbuser():
954+ ... sample_person = getUtility(IPersonSet).getByEmail(
955+ ... 'test@canonical.com')
956+ ... firefox = getUtility(IProductSet).getByName('firefox')
957+ ... bug = firefox.createBug(
958+ ... CreateBugParams(sample_person, "Yet another test bug",
959+ ... "Yet another test description.",
960+ ... subscribe_owner=False))
961+ ... bug_watch = bug.addWatch(bug_tracker, '1', sample_person)
962+ ... bug_watch_two = bug.addWatch(bug_tracker, '2', sample_person)
963+ ... bug_watch_broken = bug.addWatch(bug_tracker, '42', sample_person)
964
965
966 getCommentIds()
967
968=== modified file 'lib/lp/bugs/doc/externalbugtracker-comment-pushing.txt'
969--- lib/lp/bugs/doc/externalbugtracker-comment-pushing.txt 2011-12-29 05:29:36 +0000
970+++ lib/lp/bugs/doc/externalbugtracker-comment-pushing.txt 2012-01-24 12:44:15 +0000
971@@ -7,11 +7,10 @@
972 BugWatch, Message and BugMessage instances with which to work.
973
974 >>> from zope.interface import implements
975- >>> from lp.services.config import config
976 >>> from lp.bugs.tests.externalbugtracker import (
977 ... new_bugtracker)
978 >>> from lp.services.messages.interfaces.message import IMessageSet
979- >>> from lp.testing.layers import LaunchpadZopelessLayer
980+ >>> from lp.testing.dbuser import lp_dbuser
981 >>> from lp.bugs.interfaces.bug import CreateBugParams
982 >>> from lp.bugs.interfaces.bugmessage import IBugMessageSet
983 >>> from lp.bugs.interfaces.bugtracker import BugTrackerType
984@@ -21,24 +20,19 @@
985
986 >>> bug_tracker = new_bugtracker(BugTrackerType.TRAC)
987
988- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
989- >>> sample_person = getUtility(IPersonSet).getByEmail(
990- ... 'test@canonical.com')
991- >>> firefox = getUtility(IProductSet).getByName('firefox')
992- >>> bug = firefox.createBug(
993- ... CreateBugParams(sample_person, "A test bug",
994- ... "With a test description.",
995- ... subscribe_owner=False))
996-
997- >>> message = getUtility(IMessageSet).fromText(
998- ... "An example comment", "Pushing, for the purpose of.",
999- ... sample_person)
1000-
1001- >>> bug_watch = bug.addWatch(bug_tracker, '1234', sample_person)
1002-
1003- >>> transaction.commit()
1004-
1005- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
1006+ >>> with lp_dbuser():
1007+ ... sample_person = getUtility(IPersonSet).getByEmail(
1008+ ... 'test@canonical.com')
1009+ ... firefox = getUtility(IProductSet).getByName('firefox')
1010+ ... bug = firefox.createBug(
1011+ ... CreateBugParams(sample_person, "A test bug",
1012+ ... "With a test description.",
1013+ ... subscribe_owner=False))
1014+ ... message = getUtility(IMessageSet).fromText(
1015+ ... "An example comment", "Pushing, for the purpose of.",
1016+ ... sample_person)
1017+ ... bug_watch = bug.addWatch(bug_tracker, '1234', sample_person)
1018+
1019 >>> bug_watch = getUtility(IBugWatchSet).get(bug_watch.id)
1020 >>> bug_message = bug.linkMessage(message, bug_watch)
1021
1022@@ -98,7 +92,6 @@
1023 each Launchpad comment that needs to be pushed to the remote bug
1024 tracker.
1025
1026- >>> from lp.services.scripts.logger import log
1027 >>> from lp.bugs.scripts.checkwatches.core import CheckwatchesMaster
1028 >>> from lp.bugs.scripts.checkwatches.tests.test_bugwatchupdater import (
1029 ... make_bug_watch_updater)
1030@@ -141,15 +134,12 @@
1031 If more comments are added to the bug they will be pushed to the remote
1032 tracker the next time the bugwatch updater accesses it.
1033
1034- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
1035- >>> message_two = getUtility(IMessageSet).fromText(
1036- ... "Comment the second", "Body the second.", sample_person)
1037-
1038- >>> message_three = getUtility(IMessageSet).fromText(
1039- ... "Comment the third", "Body the third.", sample_person)
1040- >>> transaction.commit()
1041-
1042- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
1043+ >>> with lp_dbuser():
1044+ ... message_two = getUtility(IMessageSet).fromText(
1045+ ... "Comment the second", "Body the second.", sample_person)
1046+ ... message_three = getUtility(IMessageSet).fromText(
1047+ ... "Comment the third", "Body the third.", sample_person)
1048+
1049 >>> bug_watch = getUtility(IBugWatchSet).get(bug_watch.id)
1050 >>> bugmessage_two = bug.linkMessage(message_two, bug_watch)
1051 >>> bugmessage_three = bug.linkMessage(message_three, bug_watch)
1052@@ -170,11 +160,9 @@
1053 If a comment on the Launchpad bug isn't related to the bug watch, it
1054 won't be pushed.
1055
1056- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
1057- >>> message_four = getUtility(IMessageSet).fromText(
1058- ... "Comment the fourth", "Body the fourth.", sample_person)
1059- >>> transaction.commit()
1060- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
1061+ >>> with lp_dbuser():
1062+ ... message_four = getUtility(IMessageSet).fromText(
1063+ ... "Comment the fourth", "Body the fourth.", sample_person)
1064 >>> bugmessage_four = bug.linkMessage(message_four)
1065 >>> transaction.commit()
1066
1067@@ -256,12 +244,10 @@
1068 ... print "Pretending to add a comment to bug %s" % remote_bug
1069 ... return None
1070
1071- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
1072- >>> message_five = getUtility(IMessageSet).fromText(
1073- ... "Comment the fifth", "Body the fifth.", sample_person)
1074- >>> transaction.commit()
1075+ >>> with lp_dbuser():
1076+ ... message_five = getUtility(IMessageSet).fromText(
1077+ ... "Comment the fifth", "Body the fifth.", sample_person)
1078
1079- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
1080 >>> bug_watch = getUtility(IBugWatchSet).get(bug_watch.id)
1081 >>> bugmessage_five = bug.linkMessage(message_five, bug_watch)
1082 >>> transaction.commit()
1083
1084=== modified file 'lib/lp/bugs/doc/externalbugtracker-debbugs.txt'
1085--- lib/lp/bugs/doc/externalbugtracker-debbugs.txt 2011-12-30 06:14:56 +0000
1086+++ lib/lp/bugs/doc/externalbugtracker-debbugs.txt 2012-01-24 12:44:15 +0000
1087@@ -630,18 +630,15 @@
1088 >>> commit()
1089
1090 # Make sane data to play this test.
1091- >>> from lp.services.config import config
1092- >>> from lp.testing.layers import LaunchpadZopelessLayer
1093+ >>> from lp.testing.dbuser import lp_dbuser
1094 >>> from lp.registry.interfaces.distribution import IDistributionSet
1095- >>> transaction.commit()
1096- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
1097- >>> debian = getUtility(IDistributionSet).getByName('debian')
1098- >>> evolution_dsp = debian.getSourcePackage('evolution')
1099- >>> ignore = factory.makeSourcePackagePublishingHistory(
1100- ... distroseries=debian.currentseries,
1101- ... sourcepackagename=evolution_dsp.sourcepackagename)
1102- >>> transaction.commit()
1103- >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
1104+
1105+ >>> with lp_dbuser():
1106+ ... debian = getUtility(IDistributionSet).getByName('debian')
1107+ ... evolution_dsp = debian.getSourcePackage('evolution')
1108+ ... ignore = factory.makeSourcePackagePublishingHistory(
1109+ ... distroseries=debian.currentseries,
1110+ ... sourcepackagename=evolution_dsp.sourcepackagename)
1111
1112 >>> import subprocess
1113 >>> process = subprocess.Popen(
1114
1115=== modified file 'lib/lp/bugs/doc/externalbugtracker-linking-back.txt'
1116--- lib/lp/bugs/doc/externalbugtracker-linking-back.txt 2011-12-28 17:03:06 +0000
1117+++ lib/lp/bugs/doc/externalbugtracker-linking-back.txt 2012-01-24 12:44:15 +0000
1118@@ -29,10 +29,10 @@
1119
1120 The methods are called by the CheckwatchesMaster class:
1121
1122- >>> from lp.testing.layers import LaunchpadZopelessLayer
1123+ >>> from lp.testing.dbuser import switch_dbuser
1124 >>> txn = transaction
1125
1126- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
1127+ >>> switch_dbuser('launchpad')
1128
1129 >>> bug_watch = factory.makeBugWatch('42')
1130 >>> bug_watch.bug.default_bugtask.bugwatch = bug_watch
1131@@ -44,7 +44,7 @@
1132 >>> unlinked_bug = factory.makeBug()
1133
1134 >>> txn.commit()
1135- >>> LaunchpadZopelessLayer.switchDbUser('checkwatches')
1136+ >>> switch_dbuser('checkwatches')
1137
1138 >>> from lp.bugs.scripts.checkwatches import CheckwatchesMaster
1139 >>> checkwatches_master = CheckwatchesMaster(txn)
1140
1141=== modified file 'lib/lp/bugs/doc/product-update-remote-product.txt'
1142--- lib/lp/bugs/doc/product-update-remote-product.txt 2011-12-29 05:29:36 +0000
1143+++ lib/lp/bugs/doc/product-update-remote-product.txt 2012-01-24 12:44:15 +0000
1144@@ -129,34 +129,20 @@
1145 product. Products having a bug tracker of a different type than the
1146 given one are ignored.
1147
1148- >>> import transaction
1149- >>> from lp.services.config import config
1150- >>> from lp.testing.layers import LaunchpadZopelessLayer
1151-
1152- >>> def switch_db_to_launchpad():
1153- ... transaction.commit()
1154- ... LaunchpadZopelessLayer.switchDbUser('launchpad')
1155-
1156- >>> def switch_db_to_updateremoteproduct():
1157- ... transaction.commit()
1158- ... LaunchpadZopelessLayer.switchDbUser(
1159- ... config.updateremoteproduct.dbuser)
1160+ >>> from lp.testing.dbuser import lp_dbuser
1161
1162 >>> updater = NoNetworkRemoteProductUpdater(
1163 ... FakeTransaction(), BufferLogger())
1164
1165- >>> switch_db_to_launchpad()
1166-
1167- >>> bugzilla_bugtask = factory.makeBugTask(target=bugzilla_product)
1168- >>> bugzilla_bugwatch = factory.makeBugWatch(
1169- ... '42', bugtracker=bugzilla, bug=bugzilla_bugtask.bug)
1170- >>> bugzilla_bugtask.bugwatch = bugzilla_bugwatch
1171- >>> rt_bugtask = factory.makeBugTask(target=rt_product)
1172- >>> rt_bugwatch = factory.makeBugWatch(
1173- ... '84', bugtracker=rt, bug=rt_bugtask.bug)
1174- >>> rt_bugtask.bugwatch = rt_bugwatch
1175-
1176- >>> switch_db_to_updateremoteproduct()
1177+ >>> with lp_dbuser():
1178+ ... bugzilla_bugtask = factory.makeBugTask(target=bugzilla_product)
1179+ ... bugzilla_bugwatch = factory.makeBugWatch(
1180+ ... '42', bugtracker=bugzilla, bug=bugzilla_bugtask.bug)
1181+ ... bugzilla_bugtask.bugwatch = bugzilla_bugwatch
1182+ ... rt_bugtask = factory.makeBugTask(target=rt_product)
1183+ ... rt_bugwatch = factory.makeBugWatch(
1184+ ... '84', bugtracker=rt, bug=rt_bugtask.bug)
1185+ ... rt_bugtask.bugwatch = rt_bugwatch
1186
1187 >>> updater.updateByBugTrackerType(BugTrackerType.RT)
1188 Initializing DB for bugs: [u'84'].
1189@@ -173,18 +159,15 @@
1190
1191 If a product already has remote_product set, it will not be updated.
1192
1193- >>> switch_db_to_launchpad()
1194-
1195- >>> rt_product = factory.makeProduct(official_malone=False)
1196- >>> rt = factory.makeBugTracker(
1197- ... bugtrackertype=BugTrackerType.RT)
1198- >>> rt_product.bugtracker = rt
1199- >>> rt_bugtask = factory.makeBugTask(target=rt_product)
1200- >>> rt_bugwatch = factory.makeBugWatch(
1201- ... '84', bugtracker=rt, bug=rt_bugtask.bug)
1202- >>> rt_bugtask.bugwatch = rt_bugwatch
1203-
1204- >>> switch_db_to_updateremoteproduct()
1205+ >>> with lp_dbuser():
1206+ ... rt_product = factory.makeProduct(official_malone=False)
1207+ ... rt = factory.makeBugTracker(
1208+ ... bugtrackertype=BugTrackerType.RT)
1209+ ... rt_product.bugtracker = rt
1210+ ... rt_bugtask = factory.makeBugTask(target=rt_product)
1211+ ... rt_bugwatch = factory.makeBugWatch(
1212+ ... '84', bugtracker=rt, bug=rt_bugtask.bug)
1213+ ... rt_bugtask.bugwatch = rt_bugwatch
1214
1215 >>> rt_product.remote_product = u'already-set'
1216 >>> updater = NoNetworkRemoteProductUpdater(
1217@@ -200,19 +183,16 @@
1218 To avoid long-running write transactions, the transaction is committed
1219 after each product's remote_product has been updated.
1220
1221- >>> switch_db_to_launchpad()
1222-
1223- >>> for index in range(3):
1224- ... rt_product = factory.makeProduct(official_malone=False)
1225- ... rt = factory.makeBugTracker(
1226- ... bugtrackertype=BugTrackerType.RT)
1227- ... rt_product.bugtracker = rt
1228- ... rt_bugtask = factory.makeBugTask(target=rt_product)
1229- ... rt_bugwatch = factory.makeBugWatch(
1230- ... '84', bugtracker=rt, bug=rt_bugtask.bug)
1231- ... rt_bugtask.bugwatch = rt_bugwatch
1232-
1233- >>> switch_db_to_updateremoteproduct()
1234+ >>> with lp_dbuser():
1235+ ... for index in range(3):
1236+ ... rt_product = factory.makeProduct(official_malone=False)
1237+ ... rt = factory.makeBugTracker(
1238+ ... bugtrackertype=BugTrackerType.RT)
1239+ ... rt_product.bugtracker = rt
1240+ ... rt_bugtask = factory.makeBugTask(target=rt_product)
1241+ ... rt_bugwatch = factory.makeBugWatch(
1242+ ... '84', bugtracker=rt, bug=rt_bugtask.bug)
1243+ ... rt_bugtask.bugwatch = rt_bugwatch
1244
1245 >>> updater = NoNetworkRemoteProductUpdater(
1246 ... FakeTransaction(log_calls=True), BufferLogger())
1247@@ -234,17 +214,15 @@
1248 This is a simplistic approach but it means that problems with one bug
1249 tracker don't break the run for all bug trackers.
1250
1251- >>> switch_db_to_launchpad()
1252-
1253- >>> new_rt_product = factory.makeProduct(
1254- ... name='fooix', official_malone=False)
1255- >>> new_rt_product.bugtracker = rt
1256- >>> new_rt_bugtask = factory.makeBugTask(target=new_rt_product)
1257- >>> new_rt_bugwatch = factory.makeBugWatch(
1258- ... '42', bugtracker=rt, bug=new_rt_bugtask.bug)
1259- >>> new_rt_bugtask.bugwatch = new_rt_bugwatch
1260-
1261- >>> switch_db_to_updateremoteproduct()
1262+ >>> with lp_dbuser():
1263+ ... new_rt_product = factory.makeProduct(
1264+ ... name='fooix', official_malone=False)
1265+ ... new_rt_product.bugtracker = rt
1266+ ... new_rt_bugtask = factory.makeBugTask(target=new_rt_product)
1267+ ... new_rt_bugwatch = factory.makeBugWatch(
1268+ ... '42', bugtracker=rt, bug=new_rt_bugtask.bug)
1269+ ... new_rt_bugtask.bugwatch = new_rt_bugwatch
1270+
1271 >>> from lp.bugs.externalbugtracker.base import (
1272 ... BugNotFound, BugWatchUpdateError)
1273 >>> class BrokenOnInitExternalBugTracker(
1274
1275=== modified file 'lib/lp/bugs/mail/tests/test_handler.py'
1276--- lib/lp/bugs/mail/tests/test_handler.py 2011-12-30 06:14:56 +0000
1277+++ lib/lp/bugs/mail/tests/test_handler.py 2012-01-24 12:44:15 +0000
1278@@ -40,6 +40,7 @@
1279 TestCase,
1280 TestCaseWithFactory,
1281 )
1282+from lp.testing.dbuser import switch_dbuser
1283 from lp.testing.factory import GPGSigningContext
1284 from lp.testing.gpgkeys import import_secret_test_key
1285 from lp.testing.layers import (
1286@@ -164,15 +165,10 @@
1287 transaction.commit()
1288 return stub.test_emails[:]
1289
1290- def switchDbUser(self, user):
1291- """Commit the transaction and switch to the new user."""
1292- transaction.commit()
1293- LaunchpadZopelessLayer.switchDbUser(user)
1294-
1295 def getFailureForMessage(self, to_address, from_address=None, body=None):
1296 mail = self.factory.makeSignedMessage(
1297 body=body, email_address=from_address)
1298- self.switchDbUser(config.processmail.dbuser)
1299+ switch_dbuser(config.processmail.dbuser)
1300 # Rejection email goes to the preferred email of the current user.
1301 # The current user is extracted from the current interaction, which is
1302 # set up using the authenticateEmail method. However that expects
1303
1304=== modified file 'lib/lp/bugs/model/tests/test_bugsummary.py'
1305--- lib/lp/bugs/model/tests/test_bugsummary.py 2012-01-01 02:58:52 +0000
1306+++ lib/lp/bugs/model/tests/test_bugsummary.py 2012-01-24 12:44:15 +0000
1307@@ -21,6 +21,7 @@
1308 from lp.registry.model.teammembership import TeamParticipation
1309 from lp.services.database.lpstorm import IMasterStore
1310 from lp.testing import TestCaseWithFactory
1311+from lp.testing.dbuser import switch_dbuser
1312 from lp.testing.layers import LaunchpadZopelessLayer
1313
1314
1315@@ -33,7 +34,7 @@
1316
1317 # Some things we are testing are impossible as mere mortals,
1318 # but might happen from the SQL command line.
1319- LaunchpadZopelessLayer.switchDbUser('testadmin')
1320+ switch_dbuser('testadmin')
1321
1322 self.store = IMasterStore(BugSummary)
1323
1324
1325=== modified file 'lib/lp/bugs/model/tests/test_bugtask.py'
1326--- lib/lp/bugs/model/tests/test_bugtask.py 2012-01-06 16:52:46 +0000
1327+++ lib/lp/bugs/model/tests/test_bugtask.py 2012-01-24 12:44:15 +0000
1328@@ -82,6 +82,10 @@
1329 TestCaseWithFactory,
1330 ws_object,
1331 )
1332+from lp.testing.dbuser import (
1333+ dbuser,
1334+ switch_dbuser,
1335+ )
1336 from lp.testing.factory import LaunchpadObjectFactory
1337 from lp.testing.fakemethod import FakeMethod
1338 from lp.testing.layers import (
1339@@ -634,7 +638,7 @@
1340
1341 def setUp(self):
1342 super(TestBugTaskHardwareSearch, self).setUp()
1343- self.layer.switchDbUser('launchpad')
1344+ switch_dbuser('launchpad')
1345
1346 def test_search_results_without_duplicates(self):
1347 # Searching for hardware related bugtasks returns each
1348@@ -645,11 +649,9 @@
1349 self.layer.txn.commit()
1350 device = getUtility(IHWDeviceSet).getByDeviceID(
1351 HWBus.PCI, '0x10de', '0x0455')
1352- self.layer.switchDbUser('hwdb-submission-processor')
1353- self.factory.makeHWSubmissionDevice(
1354- new_submission, device, None, None, 1)
1355- self.layer.txn.commit()
1356- self.layer.switchDbUser('launchpad')
1357+ with dbuser('hwdb-submission-processor'):
1358+ self.factory.makeHWSubmissionDevice(
1359+ new_submission, device, None, None, 1)
1360 search_params = BugTaskSearchParams(
1361 user=None, hardware_bus=HWBus.PCI, hardware_vendor_id='0x10de',
1362 hardware_product_id='0x0455', hardware_owner_is_bug_reporter=True)
1363
1364=== modified file 'lib/lp/bugs/scripts/checkwatches/tests/test_core.py'
1365--- lib/lp/bugs/scripts/checkwatches/tests/test_core.py 2012-01-01 02:58:52 +0000
1366+++ lib/lp/bugs/scripts/checkwatches/tests/test_core.py 2012-01-24 12:44:15 +0000
1367@@ -47,6 +47,7 @@
1368 TestCaseWithFactory,
1369 ZopeTestInSubProcess,
1370 )
1371+from lp.testing.dbuser import switch_dbuser
1372 from lp.testing.layers import LaunchpadZopelessLayer
1373
1374
1375@@ -301,11 +302,10 @@
1376 # subscribers from a bug watch.
1377 question.subscribe(
1378 getUtility(ILaunchpadCelebrities).launchpad_developers)
1379- transaction.commit()
1380
1381 # We now need to switch to the checkwatches DB user so that
1382 # we're testing with the correct set of permissions.
1383- self.layer.switchDbUser(config.checkwatches.dbuser)
1384+ switch_dbuser(config.checkwatches.dbuser)
1385
1386 # For test_can_update_bug_with_questions we also need a bug
1387 # watch and by extension a bug tracker.
1388
1389=== modified file 'lib/lp/bugs/scripts/tests/test_bugnotification.py'
1390--- lib/lp/bugs/scripts/tests/test_bugnotification.py 2011-12-30 06:14:56 +0000
1391+++ lib/lp/bugs/scripts/tests/test_bugnotification.py 2012-01-24 12:44:15 +0000
1392@@ -80,7 +80,10 @@
1393 TestCase,
1394 TestCaseWithFactory,
1395 )
1396-from lp.testing.dbuser import lp_dbuser
1397+from lp.testing.dbuser import (
1398+ lp_dbuser,
1399+ switch_dbuser,
1400+ )
1401 from lp.testing.layers import LaunchpadZopelessLayer
1402 from lp.testing.matchers import Contains
1403
1404@@ -241,7 +244,7 @@
1405
1406 def setUp(self):
1407 """Set up some mock bug notifications to use."""
1408- self.layer.switchDbUser(config.malone.bugnotification_dbuser)
1409+ switch_dbuser(config.malone.bugnotification_dbuser)
1410 sample_person = getUtility(IPersonSet).getByEmail(
1411 'test@canonical.com')
1412 self.now = datetime.now(pytz.timezone('UTC'))
1413@@ -607,7 +610,7 @@
1414 [self.product_bugtask] = self.bug.bugtasks
1415 commit()
1416 login('test@canonical.com')
1417- self.layer.switchDbUser(config.malone.bugnotification_dbuser)
1418+ switch_dbuser(config.malone.bugnotification_dbuser)
1419 self.now = datetime.now(pytz.UTC)
1420 self.ten_minutes_ago = self.now - timedelta(minutes=10)
1421 self.notification_set = getUtility(IBugNotificationSet)
1422
1423=== modified file 'lib/lp/bugs/tests/bugs-emailinterface.txt'
1424--- lib/lp/bugs/tests/bugs-emailinterface.txt 2012-01-17 14:27:01 +0000
1425+++ lib/lp/bugs/tests/bugs-emailinterface.txt 2012-01-24 12:44:15 +0000
1426@@ -193,19 +193,16 @@
1427 It's possible to file a bug on more than product/package at once:
1428
1429 # Make sane data to play this test.
1430- >>> from lp.services.config import config
1431- >>> from lp.testing.layers import LaunchpadZopelessLayer
1432- >>> commit()
1433- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
1434 >>> from zope.component import getUtility
1435 >>> from lp.registry.interfaces.distribution import IDistributionSet
1436- >>> debian = getUtility(IDistributionSet).getByName('debian')
1437- >>> evolution_dsp = debian.getSourcePackage('evolution')
1438- >>> ignore = factory.makeSourcePackagePublishingHistory(
1439- ... distroseries=debian.currentseries,
1440- ... sourcepackagename=evolution_dsp.sourcepackagename)
1441- >>> commit()
1442- >>> LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
1443+ >>> from lp.testing.dbuser import lp_dbuser
1444+
1445+ >>> with lp_dbuser():
1446+ ... debian = getUtility(IDistributionSet).getByName('debian')
1447+ ... evolution_dsp = debian.getSourcePackage('evolution')
1448+ ... ignore = factory.makeSourcePackagePublishingHistory(
1449+ ... distroseries=debian.currentseries,
1450+ ... sourcepackagename=evolution_dsp.sourcepackagename)
1451
1452 >>> submit_mail = """From: Sample Person <test@canonical.com>
1453 ... To: new@bugs.canonical.com
1454
1455=== modified file 'lib/lp/bugs/tests/externalbugtracker.py'
1456--- lib/lp/bugs/tests/externalbugtracker.py 2011-12-30 06:14:56 +0000
1457+++ lib/lp/bugs/tests/externalbugtracker.py 2012-01-24 12:44:15 +0000
1458@@ -60,11 +60,9 @@
1459 from lp.bugs.scripts import debbugs
1460 from lp.bugs.xmlrpc.bug import ExternalBugTrackerTokenAPI
1461 from lp.registry.interfaces.person import IPersonSet
1462-from lp.services.config import config
1463-from lp.services.database.sqlbase import commit
1464 from lp.services.verification.interfaces.logintoken import ILoginTokenSet
1465 from lp.testing import celebrity_logged_in
1466-from lp.testing.layers import LaunchpadZopelessLayer
1467+from lp.testing.dbuser import lp_dbuser
1468 from lp.testing.systemdocs import ordered_dict_as_string
1469
1470
1471@@ -76,23 +74,21 @@
1472 closed. After returning from this function, a new connection using
1473 the checkwatches db user is created.
1474 """
1475- LaunchpadZopelessLayer.switchDbUser('launchpad')
1476- owner = getUtility(IPersonSet).getByEmail('no-priv@canonical.com')
1477- bugtracker_set = getUtility(IBugTrackerSet)
1478- index = 1
1479- name = '%s-checkwatches' % (bugtracker_type.name.lower())
1480- while bugtracker_set.getByName("%s-%d" % (name, index)) is not None:
1481- index += 1
1482- name += '-%d' % index
1483- BugTracker(
1484- name=name,
1485- title='%s *TESTING*' % (bugtracker_type.title),
1486- bugtrackertype=bugtracker_type,
1487- baseurl=base_url,
1488- summary='-', contactdetails='-',
1489- owner=owner)
1490- commit()
1491- LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
1492+ with lp_dbuser():
1493+ owner = getUtility(IPersonSet).getByEmail('no-priv@canonical.com')
1494+ bugtracker_set = getUtility(IBugTrackerSet)
1495+ index = 1
1496+ name = '%s-checkwatches' % (bugtracker_type.name.lower())
1497+ while bugtracker_set.getByName("%s-%d" % (name, index)) is not None:
1498+ index += 1
1499+ name += '-%d' % index
1500+ BugTracker(
1501+ name=name,
1502+ title='%s *TESTING*' % (bugtracker_type.title),
1503+ bugtrackertype=bugtracker_type,
1504+ baseurl=base_url,
1505+ summary='-', contactdetails='-',
1506+ owner=owner)
1507 return getUtility(IBugTrackerSet).getByName(name)
1508
1509
1510@@ -1195,11 +1191,8 @@
1511 def request(self, host, handler, request, verbose=None):
1512 args, method_name = xmlrpclib.loads(request)
1513 method = getattr(self, method_name)
1514- LaunchpadZopelessLayer.switchDbUser('launchpad')
1515- result = method(*args)
1516- LaunchpadZopelessLayer.txn.commit()
1517- LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
1518- return result
1519+ with lp_dbuser():
1520+ return method(*args)
1521
1522 def newBugTrackerToken(self):
1523 token_api = ExternalBugTrackerTokenAPI(None, None)
1524
1525=== modified file 'lib/lp/bugs/tests/test_bugnotification.py'
1526--- lib/lp/bugs/tests/test_bugnotification.py 2011-12-30 06:14:56 +0000
1527+++ lib/lp/bugs/tests/test_bugnotification.py 2012-01-24 12:44:15 +0000
1528@@ -40,6 +40,7 @@
1529 person_logged_in,
1530 TestCaseWithFactory,
1531 )
1532+from lp.testing.dbuser import switch_dbuser
1533 from lp.testing.factory import LaunchpadObjectFactory
1534 from lp.testing.layers import (
1535 DatabaseFunctionalLayer,
1536@@ -131,8 +132,7 @@
1537 question.linkBug(self.bug)
1538 # Flush pending jobs for question creation.
1539 pop_questionemailjobs()
1540- transaction.commit()
1541- self.layer.switchDbUser(config.malone.expiration_dbuser)
1542+ switch_dbuser(config.malone.expiration_dbuser)
1543
1544 def test_notifications_for_question_subscribers(self):
1545 # Ensure that notifications are sent to subscribers of a
1546
1547=== modified file 'lib/lp/bugs/tests/test_bugwatch.py'
1548--- lib/lp/bugs/tests/test_bugwatch.py 2011-12-30 06:14:56 +0000
1549+++ lib/lp/bugs/tests/test_bugwatch.py 2012-01-24 12:44:15 +0000
1550@@ -51,6 +51,7 @@
1551 login_person,
1552 TestCaseWithFactory,
1553 )
1554+from lp.testing.dbuser import switch_dbuser
1555 from lp.testing.layers import (
1556 DatabaseFunctionalLayer,
1557 LaunchpadFunctionalLayer,
1558@@ -641,9 +642,8 @@
1559 # where n is determined by checkwatches.scheduler.MAX_SAMPLE_SIZE.
1560 for i in range(5):
1561 self.bug_watch.addActivity(message="Activity %s" % i)
1562- transaction.commit()
1563
1564- self.layer.switchDbUser('garbo')
1565+ switch_dbuser('garbo')
1566 self.pruner = BugWatchActivityPruner(BufferLogger())
1567 self.addCleanup(self.pruner.cleanUp)
1568
1569
1570=== modified file 'lib/lp/bugs/tests/test_doc.py'
1571--- lib/lp/bugs/tests/test_doc.py 2011-12-30 06:14:56 +0000
1572+++ lib/lp/bugs/tests/test_doc.py 2012-01-24 12:44:15 +0000
1573@@ -22,6 +22,7 @@
1574 login,
1575 logout,
1576 )
1577+from lp.testing.dbuser import switch_dbuser
1578 from lp.testing.layers import (
1579 DatabaseLayer,
1580 LaunchpadFunctionalLayer,
1581@@ -47,7 +48,7 @@
1582 def checkwatchesSetUp(test):
1583 """Setup the check watches script tests."""
1584 setUp(test)
1585- LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
1586+ switch_dbuser(config.checkwatches.dbuser)
1587
1588
1589 def branchscannerBugsSetUp(test):
1590@@ -58,7 +59,7 @@
1591
1592 def bugNotificationSendingSetUp(test):
1593 lobotomize_stevea()
1594- LaunchpadZopelessLayer.switchDbUser(config.malone.bugnotification_dbuser)
1595+ switch_dbuser(config.malone.bugnotification_dbuser)
1596 setUp(test)
1597
1598
1599@@ -68,7 +69,7 @@
1600
1601 def cveSetUp(test):
1602 lobotomize_stevea()
1603- LaunchpadZopelessLayer.switchDbUser(config.cveupdater.dbuser)
1604+ switch_dbuser(config.cveupdater.dbuser)
1605 setUp(test)
1606
1607
1608@@ -81,7 +82,7 @@
1609 """
1610 lobotomize_stevea()
1611 test_dbuser = config.uploader.dbuser
1612- LaunchpadZopelessLayer.switchDbUser(test_dbuser)
1613+ switch_dbuser(test_dbuser)
1614 setUp(test)
1615 test.globs['test_dbuser'] = test_dbuser
1616
1617@@ -110,7 +111,7 @@
1618 def updateRemoteProductSetup(test):
1619 """Setup to use the 'updateremoteproduct' db user."""
1620 setUp(test)
1621- LaunchpadZopelessLayer.switchDbUser(config.updateremoteproduct.dbuser)
1622+ switch_dbuser(config.updateremoteproduct.dbuser)
1623
1624
1625 def updateRemoteProductTeardown(test):
1626
1627=== modified file 'lib/lp/buildmaster/tests/test_buildmaster_documentation.py'
1628--- lib/lp/buildmaster/tests/test_buildmaster_documentation.py 2011-12-29 05:29:36 +0000
1629+++ lib/lp/buildmaster/tests/test_buildmaster_documentation.py 2012-01-24 12:44:15 +0000
1630@@ -16,6 +16,7 @@
1631 login,
1632 logout,
1633 )
1634+from lp.testing.dbuser import switch_dbuser
1635 from lp.testing.layers import (
1636 LaunchpadFunctionalLayer,
1637 LaunchpadZopelessLayer,
1638@@ -38,7 +39,7 @@
1639 login(ANONYMOUS)
1640 setGlobs(test)
1641 test.globs['test_dbuser'] = test_dbuser
1642- LaunchpadZopelessLayer.switchDbUser(test_dbuser)
1643+ switch_dbuser(test_dbuser)
1644
1645
1646 def buildmasterTearDown(test):
1647@@ -82,7 +83,7 @@
1648
1649 for filename in sorted(filenames):
1650 test = LayeredDocFileSuite(
1651- "../doc/" +filename, setUp=buildmasterSetUp,
1652+ "../doc/" + filename, setUp=buildmasterSetUp,
1653 tearDown=buildmasterTearDown,
1654 stdout_logging_level=logging.WARNING,
1655 layer=LaunchpadZopelessLayer)
1656
1657=== modified file 'lib/lp/buildmaster/tests/test_manager.py'
1658--- lib/lp/buildmaster/tests/test_manager.py 2012-01-11 08:52:22 +0000
1659+++ lib/lp/buildmaster/tests/test_manager.py 2012-01-24 12:44:15 +0000
1660@@ -51,6 +51,7 @@
1661 TestCase,
1662 TestCaseWithFactory,
1663 )
1664+from lp.testing.dbuser import switch_dbuser
1665 from lp.testing.factory import LaunchpadObjectFactory
1666 from lp.testing.fakemethod import FakeMethod
1667 from lp.testing.layers import (
1668@@ -139,8 +140,7 @@
1669 builder.failure_count = 1
1670
1671 # Run 'scan' and check its result.
1672- self.layer.txn.commit()
1673- self.layer.switchDbUser(config.builddmaster.dbuser)
1674+ switch_dbuser(config.builddmaster.dbuser)
1675 scanner = self._getScanner()
1676 d = defer.maybeDeferred(scanner.scan)
1677 d.addCallback(self._checkDispatch, builder)
1678@@ -178,7 +178,7 @@
1679 login(ANONYMOUS)
1680
1681 # Run 'scan' and check its result.
1682- self.layer.switchDbUser(config.builddmaster.dbuser)
1683+ switch_dbuser(config.builddmaster.dbuser)
1684 scanner = self._getScanner()
1685 d = defer.maybeDeferred(scanner.singleCycle)
1686 d.addCallback(self._checkNoDispatch, builder)
1687@@ -219,7 +219,7 @@
1688 login(ANONYMOUS)
1689
1690 # Run 'scan' and check its result.
1691- self.layer.switchDbUser(config.builddmaster.dbuser)
1692+ switch_dbuser(config.builddmaster.dbuser)
1693 scanner = self._getScanner()
1694 d = defer.maybeDeferred(scanner.scan)
1695 d.addCallback(self._checkJobRescued, builder, job)
1696@@ -254,7 +254,7 @@
1697 self.assertBuildingJob(job, builder)
1698
1699 # Run 'scan' and check its result.
1700- self.layer.switchDbUser(config.builddmaster.dbuser)
1701+ switch_dbuser(config.builddmaster.dbuser)
1702 scanner = self._getScanner()
1703 d = defer.maybeDeferred(scanner.scan)
1704 d.addCallback(self._checkJobUpdated, builder, job)
1705@@ -445,7 +445,7 @@
1706 build.status = BuildStatus.CANCELLING
1707
1708 # Run 'scan' and check its results.
1709- self.layer.switchDbUser(config.builddmaster.dbuser)
1710+ switch_dbuser(config.builddmaster.dbuser)
1711 scanner = self._getScanner()
1712 d = scanner.scan()
1713
1714
1715=== modified file 'lib/lp/code/mail/tests/test_codehandler.py'
1716--- lib/lp/code/mail/tests/test_codehandler.py 2012-01-01 02:58:52 +0000
1717+++ lib/lp/code/mail/tests/test_codehandler.py 2012-01-24 12:44:15 +0000
1718@@ -73,6 +73,7 @@
1719 TestCase,
1720 TestCaseWithFactory,
1721 )
1722+from lp.testing.dbuser import switch_dbuser
1723 from lp.testing.layers import (
1724 LaunchpadZopelessLayer,
1725 ZopelessAppServerLayer,
1726@@ -164,11 +165,6 @@
1727 setSecurityPolicy(self._old_policy)
1728 super(TestCodeHandler, self).tearDown()
1729
1730- def switchDbUser(self, user):
1731- """Commit the transaction and switch to the new user."""
1732- transaction.commit()
1733- LaunchpadZopelessLayer.switchDbUser(user)
1734-
1735 def test_get(self):
1736 handler = mail_handlers.get(config.launchpad.code_domain)
1737 self.assertIsInstance(handler, CodeHandler)
1738@@ -178,7 +174,7 @@
1739 mail = self.factory.makeSignedMessage('<my-id>')
1740 bmp = self.factory.makeBranchMergeProposal()
1741 email_addr = bmp.address
1742- self.switchDbUser(config.processmail.dbuser)
1743+ switch_dbuser(config.processmail.dbuser)
1744 self.assertTrue(self.code_handler.process(
1745 mail, email_addr, None), "Succeeded, but didn't return True")
1746 # if the message has not been created, this raises SQLObjectNotFound
1747@@ -191,7 +187,7 @@
1748 bmp = self.factory.makeBranchMergeProposal(
1749 target_branch=target_branch)
1750 email_addr = bmp.address
1751- self.switchDbUser(config.processmail.dbuser)
1752+ switch_dbuser(config.processmail.dbuser)
1753 self.code_handler.process(mail, email_addr, None)
1754 self.assertIn(
1755 '<my-id>', [comment.message.rfc822msgid
1756@@ -200,14 +196,14 @@
1757 def test_processBadAddress(self):
1758 """When a bad address is supplied, it returns False."""
1759 mail = self.factory.makeSignedMessage('<my-id>')
1760- self.switchDbUser(config.processmail.dbuser)
1761+ switch_dbuser(config.processmail.dbuser)
1762 self.assertFalse(self.code_handler.process(mail,
1763 'foo@code.launchpad.dev', None))
1764
1765 def test_processNonExistantAddress(self):
1766 """When a non-existant address is supplied, it returns False."""
1767 mail = self.factory.makeSignedMessage('<my-id>')
1768- self.switchDbUser(config.processmail.dbuser)
1769+ switch_dbuser(config.processmail.dbuser)
1770 self.assertTrue(self.code_handler.process(mail,
1771 'mp+0@code.launchpad.dev', None))
1772 notification = pop_notifications()[0]
1773@@ -228,7 +224,7 @@
1774 # Remove the notifications sent about the new proposal.
1775 pop_notifications()
1776 email_addr = bmp.address
1777- self.switchDbUser(config.processmail.dbuser)
1778+ switch_dbuser(config.processmail.dbuser)
1779 self.assertTrue(self.code_handler.process(
1780 mail, email_addr, None), "Didn't return True")
1781 notification = pop_notifications()[0]
1782@@ -263,7 +259,7 @@
1783 def test_getReplyAddress(self):
1784 """getReplyAddress should return From or Reply-to address."""
1785 mail = self.factory.makeSignedMessage()
1786- self.switchDbUser(config.processmail.dbuser)
1787+ switch_dbuser(config.processmail.dbuser)
1788 self.assertEqual(
1789 mail['From'], self.code_handler._getReplyAddress(mail))
1790 mail['Reply-to'] = self.factory.getUniqueEmailAddress()
1791@@ -288,7 +284,7 @@
1792 bmp = self.factory.makeBranchMergeProposal(
1793 target_branch=code_import.branch)
1794 email_addr = bmp.address
1795- self.switchDbUser(config.processmail.dbuser)
1796+ switch_dbuser(config.processmail.dbuser)
1797 pop_notifications()
1798 self.code_handler.process(mail, email_addr, None)
1799 notification = pop_notifications()[0]
1800@@ -304,7 +300,7 @@
1801 mail = self.factory.makeSignedMessage(body=' vote Abstain EBAILIWICK')
1802 bmp = self.factory.makeBranchMergeProposal()
1803 email_addr = bmp.address
1804- self.switchDbUser(config.processmail.dbuser)
1805+ switch_dbuser(config.processmail.dbuser)
1806 self.code_handler.process(mail, email_addr, None)
1807 self.assertEqual(CodeReviewVote.ABSTAIN, bmp.all_comments[0].vote)
1808 self.assertEqual('ebailiwick', bmp.all_comments[0].vote_tag)
1809@@ -315,7 +311,7 @@
1810 body=' vote: Abstain EBAILIWICK')
1811 bmp = self.factory.makeBranchMergeProposal()
1812 email_addr = bmp.address
1813- self.switchDbUser(config.processmail.dbuser)
1814+ switch_dbuser(config.processmail.dbuser)
1815 self.code_handler.process(mail, email_addr, None)
1816 self.assertEqual(CodeReviewVote.ABSTAIN, bmp.all_comments[0].vote)
1817 self.assertEqual('ebailiwick', bmp.all_comments[0].vote_tag)
1818@@ -325,7 +321,7 @@
1819 mail = self.factory.makeSignedMessage(body=' review Abstain ROAR!')
1820 bmp = self.factory.makeBranchMergeProposal()
1821 email_addr = bmp.address
1822- self.switchDbUser(config.processmail.dbuser)
1823+ switch_dbuser(config.processmail.dbuser)
1824 self.code_handler.process(mail, email_addr, None)
1825 self.assertEqual(CodeReviewVote.ABSTAIN, bmp.all_comments[0].vote)
1826 self.assertEqual('roar!', bmp.all_comments[0].vote_tag)
1827@@ -335,7 +331,7 @@
1828 mail = self.factory.makeSignedMessage(body=' review: Abstain ROAR!')
1829 bmp = self.factory.makeBranchMergeProposal()
1830 email_addr = bmp.address
1831- self.switchDbUser(config.processmail.dbuser)
1832+ switch_dbuser(config.processmail.dbuser)
1833 self.code_handler.process(mail, email_addr, None)
1834 self.assertEqual(CodeReviewVote.ABSTAIN, bmp.all_comments[0].vote)
1835 self.assertEqual('roar!', bmp.all_comments[0].vote_tag)
1836@@ -349,7 +345,7 @@
1837 [vote] = list(bmp.votes)
1838 self.assertEqual(sender, vote.reviewer)
1839 self.assertTrue(vote.comment is None)
1840- self.switchDbUser(config.processmail.dbuser)
1841+ switch_dbuser(config.processmail.dbuser)
1842 # Login the sender as they are set as the message owner.
1843 login_person(sender)
1844 self.code_handler.process(mail, email_addr, None)
1845@@ -372,7 +368,7 @@
1846 subscriber, BranchSubscriptionNotificationLevel.NOEMAIL, None,
1847 CodeReviewNotificationLevel.FULL, subscriber)
1848 email_addr = bmp.address
1849- self.switchDbUser(config.processmail.dbuser)
1850+ switch_dbuser(config.processmail.dbuser)
1851 self.code_handler.process(mail, email_addr, None)
1852 job = Store.of(bmp).find(
1853 BranchMergeProposalJob,
1854@@ -386,13 +382,13 @@
1855 def test_getBranchMergeProposal(self):
1856 """The correct BranchMergeProposal is returned for the address."""
1857 bmp = self.factory.makeBranchMergeProposal()
1858- self.switchDbUser(config.processmail.dbuser)
1859+ switch_dbuser(config.processmail.dbuser)
1860 bmp2 = self.code_handler.getBranchMergeProposal(bmp.address)
1861 self.assertEqual(bmp, bmp2)
1862
1863 def test_getBranchMergeProposalInvalid(self):
1864 """InvalidBranchMergeProposalAddress is raised if appropriate."""
1865- self.switchDbUser(config.processmail.dbuser)
1866+ switch_dbuser(config.processmail.dbuser)
1867 self.assertRaises(InvalidBranchMergeProposalAddress,
1868 self.code_handler.getBranchMergeProposal, '')
1869 self.assertRaises(InvalidBranchMergeProposalAddress,
1870@@ -404,7 +400,7 @@
1871 source_branch = self.factory.makeAnyBranch()
1872 md = self.factory.makeMergeDirective(source_branch, target_branch)
1873 submitter = self.factory.makePerson()
1874- self.switchDbUser(config.processmail.dbuser)
1875+ switch_dbuser(config.processmail.dbuser)
1876 mp_source, mp_target = self.code_handler._acquireBranchesForProposal(
1877 md, submitter)
1878 self.assertEqual(mp_source, source_branch)
1879@@ -417,7 +413,7 @@
1880 md = self.factory.makeMergeDirective(
1881 source_branch, target_branch_url='http://example.com')
1882 submitter = self.factory.makePerson()
1883- self.switchDbUser(config.create_merge_proposals.dbuser)
1884+ switch_dbuser(config.create_merge_proposals.dbuser)
1885 self.assertRaises(
1886 NonLaunchpadTarget, self.code_handler._acquireBranchesForProposal,
1887 md, submitter)
1888@@ -436,7 +432,7 @@
1889 branches = getUtility(IBranchLookup)
1890 self.assertIs(None, branches.getByUrl(source_branch_url))
1891 submitter = self.factory.makePerson()
1892- self.switchDbUser(config.create_merge_proposals.dbuser)
1893+ switch_dbuser(config.create_merge_proposals.dbuser)
1894 mp_source, mp_target = self.code_handler._acquireBranchesForProposal(
1895 md, submitter)
1896 self.assertEqual(mp_target, target_branch)
1897@@ -461,7 +457,7 @@
1898 submitter = self.factory.makePerson()
1899 self.factory.makeProductBranch(
1900 product=target_branch.product, name='suffix', owner=submitter)
1901- self.switchDbUser(config.create_merge_proposals.dbuser)
1902+ switch_dbuser(config.create_merge_proposals.dbuser)
1903 mp_source, mp_target = self.code_handler._acquireBranchesForProposal(
1904 md, submitter)
1905 self.assertEqual('suffix-1', mp_source.name)
1906@@ -474,7 +470,7 @@
1907 body='Hi!\n', attachment_contents=''.join(md.to_lines()),
1908 force_transfer_encoding=True)
1909 code_handler = CodeHandler()
1910- self.switchDbUser(config.processmail.dbuser)
1911+ switch_dbuser(config.processmail.dbuser)
1912 comment, md2 = code_handler.findMergeDirectiveAndComment(message)
1913 self.assertEqual('Hi!\n', comment)
1914 self.assertEqual(md.revision_id, md2.revision_id)
1915@@ -489,7 +485,7 @@
1916 md = self.factory.makeMergeDirective()
1917 message = self.factory.makeSignedMessage(
1918 body='', attachment_contents=''.join(md.to_lines()))
1919- self.switchDbUser(config.processmail.dbuser)
1920+ switch_dbuser(config.processmail.dbuser)
1921 code_handler = CodeHandler()
1922 comment, md2 = code_handler.findMergeDirectiveAndComment(message)
1923 self.assertEqual('', comment)
1924@@ -503,7 +499,7 @@
1925 body = message.get_payload()[0]
1926 del body['Content-type']
1927 body.set_payload('body')
1928- self.switchDbUser(config.processmail.dbuser)
1929+ switch_dbuser(config.processmail.dbuser)
1930 code_handler = CodeHandler()
1931 comment, md2 = code_handler.findMergeDirectiveAndComment(message)
1932 self.assertEqual('body', comment)
1933@@ -519,7 +515,7 @@
1934 del body['Content-type']
1935 body['Content-type'] = 'Text/Plain'
1936 body.set_payload('body')
1937- self.switchDbUser(config.processmail.dbuser)
1938+ switch_dbuser(config.processmail.dbuser)
1939 code_handler = CodeHandler()
1940 comment, md2 = code_handler.findMergeDirectiveAndComment(message)
1941 self.assertEqual('body', comment)
1942@@ -529,7 +525,7 @@
1943 md = self.factory.makeMergeDirective()
1944 message = self.factory.makeSignedMessage(
1945 body=u'\u1234', attachment_contents=''.join(md.to_lines()))
1946- self.switchDbUser(config.processmail.dbuser)
1947+ switch_dbuser(config.processmail.dbuser)
1948 code_handler = CodeHandler()
1949 comment, md2 = code_handler.findMergeDirectiveAndComment(message)
1950 self.assertEqual(u'\u1234', comment)
1951@@ -541,7 +537,7 @@
1952 MissingMergeDirective is raised when no merge directive is present.
1953 """
1954 message = self.factory.makeSignedMessage(body='Hi!\n')
1955- self.switchDbUser(config.processmail.dbuser)
1956+ switch_dbuser(config.processmail.dbuser)
1957 code_handler = CodeHandler()
1958 self.assertRaises(MissingMergeDirective,
1959 code_handler.findMergeDirectiveAndComment, message)
1960@@ -553,7 +549,7 @@
1961 self.factory.makeMergeDirectiveEmail())
1962 # Add some revisions so the proposal is ready.
1963 self.factory.makeRevisionsForBranch(source, count=1)
1964- self.switchDbUser(config.create_merge_proposals.dbuser)
1965+ switch_dbuser(config.create_merge_proposals.dbuser)
1966 code_handler = CodeHandler()
1967 pop_notifications()
1968 bmp = code_handler.processMergeProposal(message)
1969@@ -576,7 +572,7 @@
1970 """
1971 message, file_alias, source_branch, target_branch = (
1972 self.factory.makeMergeDirectiveEmail(body=' '))
1973- self.switchDbUser(config.create_merge_proposals.dbuser)
1974+ switch_dbuser(config.create_merge_proposals.dbuser)
1975 code_handler = CodeHandler()
1976 bmp = code_handler.processMergeProposal(message)
1977 self.assertEqual(source_branch, bmp.source_branch)
1978@@ -591,8 +587,7 @@
1979 self.factory.makeMergeDirectiveEmail())
1980 # Ensure the message is stored in the librarian.
1981 # mail.incoming.handleMail also explicitly does this.
1982- transaction.commit()
1983- self.switchDbUser(config.create_merge_proposals.dbuser)
1984+ switch_dbuser(config.create_merge_proposals.dbuser)
1985 code_handler = CodeHandler()
1986 # In order to fake a non-gpg signed email, we say that the current
1987 # principal direcly provides IWeaklyAuthenticatePrincipal, which is
1988@@ -631,11 +626,11 @@
1989 self.factory.makeMergeDirectiveEmail())
1990 # Ensure the message is stored in the librarian.
1991 # mail.incoming.handleMail also explicitly does this.
1992- self.switchDbUser(config.processmail.dbuser)
1993+ switch_dbuser(config.processmail.dbuser)
1994 code_handler = CodeHandler()
1995 self.assertEqual(0, source.landing_targets.count())
1996 code_handler.process(message, 'merge@code.launchpad.net', file_alias)
1997- self.switchDbUser(config.create_merge_proposals.dbuser)
1998+ switch_dbuser(config.create_merge_proposals.dbuser)
1999 JobRunner.fromReady(CreateMergeProposalJob).runAll()
2000 self.assertEqual(target, source.landing_targets[0].target_branch)
2001 # Ensure the DB operations violate no constraints.
2002@@ -647,11 +642,11 @@
2003 self.factory.makeMergeDirectiveEmail(body=u'\u1234'))
2004 # Ensure the message is stored in the librarian.
2005 # mail.incoming.handleMail also explicitly does this.
2006- self.switchDbUser(config.processmail.dbuser)
2007+ switch_dbuser(config.processmail.dbuser)
2008 code_handler = CodeHandler()
2009 self.assertEqual(0, source.landing_targets.count())
2010 code_handler.process(message, 'merge@code.launchpad.net', file_alias)
2011- self.switchDbUser(config.create_merge_proposals.dbuser)
2012+ switch_dbuser(config.create_merge_proposals.dbuser)
2013 JobRunner.fromReady(CreateMergeProposalJob).runAll()
2014 proposal = source.landing_targets[0]
2015 self.assertEqual(u'\u1234', proposal.description)
2016@@ -667,7 +662,7 @@
2017
2018 reviewer eric
2019 """)))
2020- self.switchDbUser(config.create_merge_proposals.dbuser)
2021+ switch_dbuser(config.create_merge_proposals.dbuser)
2022 code_handler = CodeHandler()
2023 pop_notifications()
2024 bmp = code_handler.processMergeProposal(message)
2025@@ -695,7 +690,7 @@
2026 eric = self.factory.makePerson(name="eric", email="eric@example.com")
2027 mail = self.factory.makeSignedMessage(body=' reviewer eric')
2028 email_addr = bmp.address
2029- self.switchDbUser(config.processmail.dbuser)
2030+ switch_dbuser(config.processmail.dbuser)
2031 self.code_handler.process(mail, email_addr, None)
2032 [vote] = bmp.votes
2033 self.assertEqual(eric, vote.reviewer)
2034@@ -707,7 +702,7 @@
2035 self.factory.makeMergeDirectiveEmail(body=dedent("""\
2036 This is the comment.
2037 """)))
2038- self.switchDbUser(config.create_merge_proposals.dbuser)
2039+ switch_dbuser(config.create_merge_proposals.dbuser)
2040 code_handler = CodeHandler()
2041 pop_notifications()
2042 bmp = code_handler.processMergeProposal(message)
2043@@ -732,7 +727,7 @@
2044 """
2045 message, file_alias, source, target = (
2046 self.factory.makeMergeDirectiveEmail())
2047- self.switchDbUser(config.create_merge_proposals.dbuser)
2048+ switch_dbuser(config.create_merge_proposals.dbuser)
2049 code_handler = CodeHandler()
2050 code_handler.processMergeProposal(message)
2051 pop_notifications()
2052@@ -752,7 +747,7 @@
2053 """
2054 message = self.factory.makeSignedMessage(body='A body',
2055 subject='A subject', attachment_contents='')
2056- self.switchDbUser(config.create_merge_proposals.dbuser)
2057+ switch_dbuser(config.create_merge_proposals.dbuser)
2058 code_handler = CodeHandler()
2059 code_handler.processMergeProposal(message)
2060 transaction.commit()
2061@@ -838,7 +833,7 @@
2062 subject='This is gonna fail', attachment_contents=''.join(
2063 directive.to_lines()))
2064
2065- self.switchDbUser(config.create_merge_proposals.dbuser)
2066+ switch_dbuser(config.create_merge_proposals.dbuser)
2067 code_handler = CodeHandler()
2068 code_handler.processMergeProposal(message)
2069 transaction.commit()
2070@@ -863,7 +858,7 @@
2071 bmp = self.factory.makeBranchMergeProposal()
2072 pop_notifications()
2073 email_addr = bmp.address
2074- self.switchDbUser(config.processmail.dbuser)
2075+ switch_dbuser(config.processmail.dbuser)
2076 self.code_handler.process(mail, email_addr, None)
2077 [notification] = pop_notifications()
2078
2079@@ -893,11 +888,6 @@
2080 setSecurityPolicy(self._old_policy)
2081 TestCaseWithFactory.tearDown(self)
2082
2083- def switchDbUser(self, user):
2084- """Commit the transactionand switch to the new user."""
2085- transaction.commit()
2086- LaunchpadZopelessLayer.switchDbUser(user)
2087-
2088 def _createTargetSourceAndBundle(self, format=None):
2089 """Create a merge directive with a bundle and associated branches.
2090
2091@@ -939,7 +929,7 @@
2092
2093 def _processMergeDirective(self, message):
2094 """Process the merge directive email."""
2095- self.switchDbUser(config.create_merge_proposals.dbuser)
2096+ switch_dbuser(config.create_merge_proposals.dbuser)
2097 code_handler = CodeHandler()
2098 # Do the authentication dance as we do in the processing script.
2099 authutil = getUtility(IPlacelessAuthUtility)
2100@@ -1251,8 +1241,7 @@
2101 self.context = CodeReviewEmailCommandExecutionContext(
2102 self.merge_proposal, self.merge_proposal.target_branch.owner)
2103 self.jrandom = self.factory.makePerson()
2104- transaction.commit()
2105- self.layer.switchDbUser(config.processmail.dbuser)
2106+ switch_dbuser(config.processmail.dbuser)
2107
2108 def tearDown(self):
2109 setSecurityPolicy(self._old_policy)
2110@@ -1376,8 +1365,7 @@
2111 self.context = CodeReviewEmailCommandExecutionContext(
2112 self.merge_proposal, self.merge_proposal.target_branch.owner)
2113 self.reviewer = self.factory.makePerson()
2114- transaction.commit()
2115- self.layer.switchDbUser(config.processmail.dbuser)
2116+ switch_dbuser(config.processmail.dbuser)
2117
2118 def tearDown(self):
2119 setSecurityPolicy(self._old_policy)
2120
2121=== modified file 'lib/lp/code/model/tests/test_branch_privacy_triggers.py'
2122--- lib/lp/code/model/tests/test_branch_privacy_triggers.py 2011-12-30 06:14:56 +0000
2123+++ lib/lp/code/model/tests/test_branch_privacy_triggers.py 2012-01-24 12:44:15 +0000
2124@@ -9,6 +9,7 @@
2125 import unittest
2126
2127 from lp.services.database.sqlbase import cursor
2128+from lp.testing.dbuser import switch_dbuser
2129 from lp.testing.layers import LaunchpadZopelessLayer
2130
2131
2132@@ -17,7 +18,7 @@
2133 layer = LaunchpadZopelessLayer
2134
2135 def setUp(self):
2136- LaunchpadZopelessLayer.switchDbUser('testadmin')
2137+ switch_dbuser('testadmin')
2138 self.branch_ids = dict()
2139
2140 def createBranches(self):
2141
2142=== modified file 'lib/lp/code/model/tests/test_branchjob.py'
2143--- lib/lp/code/model/tests/test_branchjob.py 2011-12-30 06:14:56 +0000
2144+++ lib/lp/code/model/tests/test_branchjob.py 2012-01-24 12:44:15 +0000
2145@@ -73,6 +73,10 @@
2146 from lp.services.osutils import override_environ
2147 from lp.services.webapp import canonical_url
2148 from lp.testing import TestCaseWithFactory
2149+from lp.testing.dbuser import (
2150+ dbuser,
2151+ switch_dbuser,
2152+ )
2153 from lp.testing.layers import (
2154 DatabaseFunctionalLayer,
2155 LaunchpadZopelessLayer,
2156@@ -146,9 +150,8 @@
2157 LaunchpadZopelessLayer.commit()
2158
2159 job = BranchScanJob.create(db_branch)
2160- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2161- job.run()
2162- LaunchpadZopelessLayer.switchDbUser(config.launchpad.dbuser)
2163+ with dbuser(config.branchscanner.dbuser):
2164+ job.run()
2165
2166 self.assertEqual(db_branch.revision_count, 3)
2167
2168@@ -156,8 +159,8 @@
2169 bzr_tree.commit('Fifth commit', rev_id='rev5')
2170
2171 job = BranchScanJob.create(db_branch)
2172- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2173- job.run()
2174+ with dbuser(config.branchscanner.dbuser):
2175+ job.run()
2176
2177 self.assertEqual(db_branch.revision_count, 5)
2178
2179@@ -416,8 +419,7 @@
2180 tree.commit('rev1', rev_id='rev1')
2181 tree.commit('rev2', rev_id='rev2')
2182 tree.commit('rev3', rev_id='rev3')
2183- transaction.commit()
2184- self.layer.switchDbUser('branchscanner')
2185+ switch_dbuser('branchscanner')
2186 self.updateDBRevisions(
2187 branch, tree.branch, ['rev1', 'rev2', 'rev3'])
2188 finally:
2189@@ -652,9 +654,8 @@
2190 def test_getRevisionMessage_with_related_BMP(self):
2191 """Information about related proposals is displayed."""
2192 job, bmp = self.makeJobAndBMP()
2193- transaction.commit()
2194- self.layer.switchDbUser(config.sendbranchmail.dbuser)
2195- message = job.getRevisionMessage('rev2d-id', 1)
2196+ with dbuser(config.sendbranchmail.dbuser):
2197+ message = job.getRevisionMessage('rev2d-id', 1)
2198 self.assertEqual(
2199 'Merge authors:\n'
2200 ' bar@\n'
2201@@ -676,9 +677,8 @@
2202 """Superseded proposals are skipped."""
2203 job, bmp = self.makeJobAndBMP()
2204 bmp2 = bmp.resubmit(bmp.registrant)
2205- transaction.commit()
2206- self.layer.switchDbUser(config.sendbranchmail.dbuser)
2207- message = job.getRevisionMessage('rev2d-id', 1)
2208+ with dbuser(config.sendbranchmail.dbuser):
2209+ message = job.getRevisionMessage('rev2d-id', 1)
2210 self.assertEqual(
2211 'Merge authors:\n'
2212 ' bar@\n'
2213@@ -705,9 +705,8 @@
2214 job, bmp = self.makeJobAndBMP()
2215 reviewer = self.factory.makePerson()
2216 bmp.nominateReviewer(reviewer, bmp.registrant)
2217- transaction.commit()
2218- self.layer.switchDbUser(config.sendbranchmail.dbuser)
2219- message = job.getRevisionMessage('rev2d-id', 1)
2220+ with dbuser(config.sendbranchmail.dbuser):
2221+ message = job.getRevisionMessage('rev2d-id', 1)
2222 self.assertEqual(
2223 'Merge authors:\n'
2224 ' bar@\n'
2225@@ -776,8 +775,7 @@
2226 rev_id=second_revision, message="Extended contents",
2227 committer="Joe Bloggs <joe@example.com>",
2228 timestamp=1000100000.0, timezone=0)
2229- transaction.commit()
2230- self.layer.switchDbUser('branchscanner')
2231+ switch_dbuser('branchscanner')
2232 self.updateDBRevisions(db_branch, tree.branch)
2233 expected = (
2234 u"-" * 60 + '\n'
2235@@ -820,8 +818,7 @@
2236 rev_id=rev_id, message=u"Non ASCII: \xe9",
2237 committer=u"Non ASCII: \xed", timestamp=1000000000.0,
2238 timezone=0)
2239- transaction.commit()
2240- self.layer.switchDbUser('branchscanner')
2241+ switch_dbuser('branchscanner')
2242 self.updateDBRevisions(db_branch, tree.branch)
2243 job = RevisionsAddedJob.create(db_branch, '', '', '')
2244 message = job.getRevisionMessage(rev_id, 1)
2245@@ -850,7 +847,7 @@
2246
2247 def test_only_nodiff_subscribers_means_no_diff_generated(self):
2248 """No diff is generated when no subscribers need it."""
2249- self.layer.switchDbUser('launchpad')
2250+ switch_dbuser('launchpad')
2251 self.useBzrBranches(direct_database=True)
2252 branch, tree = self.create_branch_and_tree()
2253 subscriptions = branch.getSubscriptionsByLevel(
2254@@ -1280,10 +1277,7 @@
2255 def runReadyJobs(self):
2256 """Run all ready `ReclaimBranchSpaceJob`s with the appropriate dbuser.
2257 """
2258- # switchDbUser aborts the current transaction, so we need to commit to
2259- # make sure newly added jobs are still there after we call it.
2260- self.layer.txn.commit()
2261- self.layer.switchDbUser(config.reclaimbranchspace.dbuser)
2262+ switch_dbuser(config.reclaimbranchspace.dbuser)
2263 job_count = 0
2264 for job in ReclaimBranchSpaceJob.iterReady():
2265 job.run()
2266
2267=== modified file 'lib/lp/code/model/tests/test_branchmergeproposaljobs.py'
2268--- lib/lp/code/model/tests/test_branchmergeproposaljobs.py 2012-01-01 02:58:52 +0000
2269+++ lib/lp/code/model/tests/test_branchmergeproposaljobs.py 2012-01-24 12:44:15 +0000
2270@@ -64,6 +64,7 @@
2271 EventRecorder,
2272 TestCaseWithFactory,
2273 )
2274+from lp.testing.dbuser import dbuser
2275 from lp.testing.layers import LaunchpadZopelessLayer
2276 from lp.testing.mail_helpers import pop_notifications
2277
2278@@ -173,9 +174,8 @@
2279 self.createBzrBranch(bmp.source_branch, tree.branch)
2280 self.factory.makeRevisionsForBranch(bmp.source_branch, count=1)
2281 job = MergeProposalNeedsReviewEmailJob.create(bmp)
2282- transaction.commit()
2283- self.layer.switchDbUser(config.merge_proposal_jobs.dbuser)
2284- job.run()
2285+ with dbuser(config.merge_proposal_jobs.dbuser):
2286+ job.run()
2287
2288
2289 class TestUpdatePreviewDiffJob(DiffTestCase):
2290@@ -206,10 +206,8 @@
2291 job = UpdatePreviewDiffJob.create(bmp)
2292 self.factory.makeRevisionsForBranch(bmp.source_branch, count=1)
2293 bmp.source_branch.next_mirror_time = None
2294- transaction.commit()
2295- self.layer.switchDbUser(config.merge_proposal_jobs.dbuser)
2296- JobRunner([job]).runAll()
2297- transaction.commit()
2298+ with dbuser(config.merge_proposal_jobs.dbuser):
2299+ JobRunner([job]).runAll()
2300 self.checkExampleMerge(bmp.preview_diff.text)
2301
2302 def test_run_object_events(self):
2303@@ -220,10 +218,9 @@
2304 job = UpdatePreviewDiffJob.create(bmp)
2305 self.factory.makeRevisionsForBranch(bmp.source_branch, count=1)
2306 bmp.source_branch.next_mirror_time = None
2307- transaction.commit()
2308- self.layer.switchDbUser(config.merge_proposal_jobs.dbuser)
2309- with EventRecorder() as event_recorder:
2310- JobRunner([job]).runAll()
2311+ with dbuser(config.merge_proposal_jobs.dbuser):
2312+ with EventRecorder() as event_recorder:
2313+ JobRunner([job]).runAll()
2314 bmp_object_events = [
2315 event for event in event_recorder.events
2316 if (IObjectModifiedEvent.providedBy(event) and
2317@@ -322,18 +319,15 @@
2318 def test_run(self):
2319 """The job runs successfully, and its results can be committed."""
2320 job = make_runnable_incremental_diff_job(self)
2321- transaction.commit()
2322- self.layer.switchDbUser(config.merge_proposal_jobs.dbuser)
2323- job.run()
2324- transaction.commit()
2325+ with dbuser(config.merge_proposal_jobs.dbuser):
2326+ job.run()
2327
2328 def test_run_all(self):
2329 """The job can be run under the JobRunner successfully."""
2330 job = make_runnable_incremental_diff_job(self)
2331- transaction.commit()
2332- self.layer.switchDbUser(config.merge_proposal_jobs.dbuser)
2333- runner = JobRunner([job])
2334- runner.runAll()
2335+ with dbuser(config.merge_proposal_jobs.dbuser):
2336+ runner = JobRunner([job])
2337+ runner.runAll()
2338 self.assertEqual([job], runner.completed_jobs)
2339
2340 def test_10_minute_lease(self):
2341@@ -341,9 +335,8 @@
2342 self.useBzrBranches(direct_database=True)
2343 bmp = create_example_merge(self)[0]
2344 job = GenerateIncrementalDiffJob.create(bmp, 'old', 'new')
2345- transaction.commit()
2346- self.layer.switchDbUser(config.merge_proposal_jobs.dbuser)
2347- job.acquireLease()
2348+ with dbuser(config.merge_proposal_jobs.dbuser):
2349+ job.acquireLease()
2350 expiry_delta = job.lease_expires - datetime.now(pytz.UTC)
2351 self.assertTrue(500 <= expiry_delta.seconds, expiry_delta)
2352
2353
2354=== modified file 'lib/lp/code/model/tests/test_revisionauthor.py'
2355--- lib/lp/code/model/tests/test_revisionauthor.py 2012-01-01 02:58:52 +0000
2356+++ lib/lp/code/model/tests/test_revisionauthor.py 2012-01-24 12:44:15 +0000
2357@@ -18,6 +18,10 @@
2358 from lp.services.identity.interfaces.emailaddress import EmailAddressStatus
2359 from lp.services.log.logger import DevNullLogger
2360 from lp.testing import TestCase
2361+from lp.testing.dbuser import (
2362+ dbuser,
2363+ switch_dbuser,
2364+ )
2365 from lp.testing.factory import LaunchpadObjectFactory
2366 from lp.testing.layers import LaunchpadZopelessLayer
2367
2368@@ -35,7 +39,7 @@
2369
2370 def setUp(self):
2371 super(TestRevisionEmailExtraction, self).setUp()
2372- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2373+ switch_dbuser(config.branchscanner.dbuser)
2374
2375 def test_email_extracted_from_name(self):
2376 # Check that a valid email address is extracted from the name.
2377@@ -87,8 +91,7 @@
2378 """
2379
2380 def _createRevisionAuthor(self):
2381- transaction.commit()
2382- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2383+ switch_dbuser(config.branchscanner.dbuser)
2384 return RevisionSet()._createRevisionAuthor(
2385 '"Harry Potter" <harry@canonical.com>')
2386
2387@@ -135,12 +138,9 @@
2388 def setUp(self):
2389 # Create a revision author that doesn't have a user yet.
2390 super(TestNewlyValidatedEmailsLinkRevisionAuthors, self).setUp()
2391- launchpad_dbuser = config.launchpad.dbuser
2392- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2393- self.author = RevisionSet()._createRevisionAuthor(
2394- '"Harry Potter" <harry@canonical.com>')
2395- transaction.commit()
2396- LaunchpadZopelessLayer.switchDbUser(launchpad_dbuser)
2397+ with dbuser(config.branchscanner.dbuser):
2398+ self.author = RevisionSet()._createRevisionAuthor(
2399+ '"Harry Potter" <harry@canonical.com>')
2400 # Reget the revision author as we have crossed a transaction boundary.
2401 self.author = RevisionAuthor.byName(self.author.name)
2402
2403@@ -175,7 +175,7 @@
2404
2405 def setUp(self):
2406 super(TestRevisionAuthor, self).setUp()
2407- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2408+ switch_dbuser(config.branchscanner.dbuser)
2409
2410 def testGetNameWithoutEmailReturnsNamePart(self):
2411 # name_without_email is equal to the 'name' part of the revision
2412
2413=== modified file 'lib/lp/code/scripts/tests/test_revisionkarma.py'
2414--- lib/lp/code/scripts/tests/test_revisionkarma.py 2012-01-05 00:23:45 +0000
2415+++ lib/lp/code/scripts/tests/test_revisionkarma.py 2012-01-24 12:44:15 +0000
2416@@ -16,6 +16,7 @@
2417 from lp.services.identity.model.emailaddress import EmailAddressSet
2418 from lp.services.log.logger import DevNullLogger
2419 from lp.testing import TestCaseWithFactory
2420+from lp.testing.dbuser import switch_dbuser
2421 from lp.testing.layers import LaunchpadZopelessLayer
2422
2423
2424@@ -51,7 +52,7 @@
2425 branch.setTarget(user=branch.owner, project=project)
2426 # Commit and switch to the script db user.
2427 transaction.commit()
2428- LaunchpadZopelessLayer.switchDbUser(config.revisionkarma.dbuser)
2429+ switch_dbuser(config.revisionkarma.dbuser)
2430 script = RevisionKarmaAllocator(
2431 'test', config.revisionkarma.dbuser, ['-q'])
2432 script.main()
2433@@ -76,7 +77,7 @@
2434 transaction.commit()
2435 # Run the RevisionAuthorEmailLinker garbo job.
2436 RevisionAuthorEmailLinker(log=DevNullLogger()).run()
2437- LaunchpadZopelessLayer.switchDbUser(config.revisionkarma.dbuser)
2438+ switch_dbuser(config.revisionkarma.dbuser)
2439 script = RevisionKarmaAllocator(
2440 'test', config.revisionkarma.dbuser, ['-q'])
2441 script.main()
2442@@ -115,8 +116,7 @@
2443 [rev], list(RevisionSet.getRevisionsNeedingKarmaAllocated()))
2444
2445 # Commit and switch to the script db user.
2446- transaction.commit()
2447- LaunchpadZopelessLayer.switchDbUser(config.revisionkarma.dbuser)
2448+ switch_dbuser(config.revisionkarma.dbuser)
2449 script = RevisionKarmaAllocator(
2450 'test', config.revisionkarma.dbuser, ['-q'])
2451 script.main()
2452
2453=== modified file 'lib/lp/code/tests/test_doc.py'
2454--- lib/lp/code/tests/test_doc.py 2012-01-01 02:58:52 +0000
2455+++ lib/lp/code/tests/test_doc.py 2012-01-24 12:44:15 +0000
2456@@ -12,6 +12,7 @@
2457 from lp.services.config import config
2458 from lp.services.testing import build_test_suite
2459 from lp.services.webapp.authorization import LaunchpadSecurityPolicy
2460+from lp.testing.dbuser import switch_dbuser
2461 from lp.testing.layers import (
2462 LaunchpadFunctionalLayer,
2463 LaunchpadZopelessLayer,
2464@@ -29,16 +30,16 @@
2465
2466 def branchscannerSetUp(test):
2467 """Setup the user for the branch scanner tests."""
2468- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2469+ switch_dbuser(config.branchscanner.dbuser)
2470 setUp(test)
2471
2472
2473 def zopelessLaunchpadSecuritySetUp(test):
2474 """Set up a LaunchpadZopelessLayer test to use LaunchpadSecurityPolicy.
2475
2476- To be able to use LaunchpadZopelessLayer.switchDbUser in a test, we need
2477- to run in the Zopeless environment. The Zopeless environment normally runs
2478- using the LaunchpadPermissiveSecurityPolicy. If we want the test to cover
2479+ To be able to use switch_dbuser in a test, we need to run in the
2480+ Zopeless environment. The Zopeless environment normally runs using the
2481+ LaunchpadPermissiveSecurityPolicy. If we want the test to cover
2482 functionality used in the webapp, it needs to use the
2483 LaunchpadSecurityPolicy.
2484 """
2485
2486=== modified file 'lib/lp/codehosting/scanner/tests/test_buglinks.py'
2487--- lib/lp/codehosting/scanner/tests/test_buglinks.py 2012-01-01 02:58:52 +0000
2488+++ lib/lp/codehosting/scanner/tests/test_buglinks.py 2012-01-24 12:44:15 +0000
2489@@ -24,6 +24,10 @@
2490 TestCase,
2491 TestCaseWithFactory,
2492 )
2493+from lp.testing.dbuser import (
2494+ lp_dbuser,
2495+ switch_dbuser,
2496+ )
2497 from lp.testing.layers import LaunchpadZopelessLayer
2498
2499
2500@@ -163,14 +167,10 @@
2501 self.assertBugBranchLinked(self.bug1, self.db_branch)
2502
2503 def makePackageBranch(self):
2504- LaunchpadZopelessLayer.switchDbUser(self.lp_db_user)
2505- try:
2506+ with lp_dbuser():
2507 branch = self.factory.makePackageBranch()
2508 branch.sourcepackage.setBranch(
2509 PackagePublishingPocket.RELEASE, branch, branch.owner)
2510- LaunchpadZopelessLayer.txn.commit()
2511- finally:
2512- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2513 return branch
2514
2515 def test_linking_bug_to_official_package_branch(self):
2516@@ -264,8 +264,7 @@
2517 self.useBzrBranches(direct_database=True)
2518 db_branch, tree = self.create_branch_and_tree()
2519 bug = self.factory.makeBug()
2520- self.layer.txn.commit()
2521- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2522+ switch_dbuser(config.branchscanner.dbuser)
2523 # XXX: AaronBentley 2010-08-06 bug=614404: a bzr username is
2524 # required to generate the revision-id.
2525 with override_environ(BZR_EMAIL='me@example.com'):
2526
2527=== modified file 'lib/lp/codehosting/scanner/tests/test_bzrsync.py'
2528--- lib/lp/codehosting/scanner/tests/test_bzrsync.py 2012-01-01 02:58:52 +0000
2529+++ lib/lp/codehosting/scanner/tests/test_bzrsync.py 2012-01-24 12:44:15 +0000
2530@@ -18,7 +18,6 @@
2531 from bzrlib.uncommit import uncommit
2532 import pytz
2533 from storm.locals import Store
2534-import transaction
2535 from twisted.python.util import mergeFunctionMetadata
2536 from zope.component import getUtility
2537 from zope.security.proxy import removeSecurityProxy
2538@@ -50,7 +49,11 @@
2539 temp_dir,
2540 TestCaseWithFactory,
2541 )
2542-from lp.testing.dbuser import dbuser
2543+from lp.testing.dbuser import (
2544+ dbuser,
2545+ lp_dbuser,
2546+ switch_dbuser,
2547+ )
2548 from lp.testing.layers import LaunchpadZopelessLayer
2549 from lp.translations.interfaces.translations import (
2550 TranslationsBranchImportMode,
2551@@ -83,9 +86,8 @@
2552 SafeBranchOpener.install_hook()
2553 self.disable_directory_isolation()
2554 self.useBzrBranches(direct_database=True)
2555- self.lp_db_user = config.launchpad.dbuser
2556 self.makeFixtures()
2557- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2558+ switch_dbuser(config.branchscanner.dbuser)
2559 # Catch both constraints and permissions for the db user.
2560 self.addCleanup(Store.of(self.db_branch).flush)
2561
2562@@ -224,33 +226,30 @@
2563 :return: (db_trunk, trunk_tree), (db_branch, branch_tree).
2564 """
2565
2566- LaunchpadZopelessLayer.switchDbUser(self.lp_db_user)
2567-
2568- # Make the base revision.
2569- db_branch = self.makeDatabaseBranch()
2570- db_branch, trunk_tree = self.create_branch_and_tree(
2571- db_branch=db_branch)
2572- # XXX: AaronBentley 2010-08-06 bug=614404: a bzr username is
2573- # required to generate the revision-id.
2574- with override_environ(BZR_EMAIL='me@example.com'):
2575- trunk_tree.commit(u'base revision', rev_id=base_rev_id)
2576-
2577- # Branch from the base revision.
2578- new_db_branch = self.makeDatabaseBranch(product=db_branch.product)
2579- new_db_branch, branch_tree = self.create_branch_and_tree(
2580- db_branch=new_db_branch)
2581- branch_tree.pull(trunk_tree.branch)
2582-
2583- # Commit to both branches.
2584- trunk_tree.commit(u'trunk revision', rev_id=trunk_rev_id)
2585- branch_tree.commit(u'branch revision', rev_id=branch_rev_id)
2586-
2587- # Merge branch into trunk.
2588- trunk_tree.merge_from_branch(branch_tree.branch)
2589- trunk_tree.commit(u'merge revision', rev_id=merge_rev_id)
2590-
2591- LaunchpadZopelessLayer.txn.commit()
2592- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2593+ with lp_dbuser():
2594+ # Make the base revision.
2595+ db_branch = self.makeDatabaseBranch()
2596+ db_branch, trunk_tree = self.create_branch_and_tree(
2597+ db_branch=db_branch)
2598+ # XXX: AaronBentley 2010-08-06 bug=614404: a bzr username is
2599+ # required to generate the revision-id.
2600+ with override_environ(BZR_EMAIL='me@example.com'):
2601+ trunk_tree.commit(u'base revision', rev_id=base_rev_id)
2602+
2603+ # Branch from the base revision.
2604+ new_db_branch = self.makeDatabaseBranch(
2605+ product=db_branch.product)
2606+ new_db_branch, branch_tree = self.create_branch_and_tree(
2607+ db_branch=new_db_branch)
2608+ branch_tree.pull(trunk_tree.branch)
2609+
2610+ # Commit to both branches.
2611+ trunk_tree.commit(u'trunk revision', rev_id=trunk_rev_id)
2612+ branch_tree.commit(u'branch revision', rev_id=branch_rev_id)
2613+
2614+ # Merge branch into trunk.
2615+ trunk_tree.merge_from_branch(branch_tree.branch)
2616+ trunk_tree.commit(u'merge revision', rev_id=merge_rev_id)
2617
2618 return (db_branch, trunk_tree), (new_db_branch, branch_tree)
2619
2620@@ -623,15 +622,11 @@
2621 """Switch to the Launchpad db user to create and configure a
2622 product series that is linked to the the branch.
2623 """
2624- try:
2625- LaunchpadZopelessLayer.switchDbUser(self.lp_db_user)
2626+ with lp_dbuser():
2627 self.product_series = self.factory.makeProductSeries()
2628 self.product_series.branch = self.db_branch
2629 if mode is not None:
2630 self.product_series.translations_autoimport_mode = mode
2631- transaction.commit()
2632- finally:
2633- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2634
2635 def test_upload_on_new_revision_no_series(self):
2636 # Syncing a branch with a changed tip does not create a
2637@@ -680,8 +675,7 @@
2638 bmp.next_preview_diff_job.start()
2639 bmp.next_preview_diff_job.complete()
2640 self.assertIs(None, bmp.next_preview_diff_job)
2641- transaction.commit()
2642- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2643+ switch_dbuser(config.branchscanner.dbuser)
2644 self.makeBzrSync(self.db_branch).syncBranchAndClose()
2645 self.assertIsNot(None, bmp.next_preview_diff_job)
2646
2647@@ -712,8 +706,7 @@
2648 revision_id = commit_file(self.db_branch, 'foo', 'baz')
2649 removeSecurityProxy(bmp).target_branch.last_scanned_id = 'rev'
2650 self.assertEqual([], self.getPending())
2651- transaction.commit()
2652- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2653+ switch_dbuser(config.branchscanner.dbuser)
2654 self.makeBzrSync(self.db_branch).syncBranchAndClose()
2655 (job,) = self.getPending()
2656 self.assertEqual(revision_id, job.new_revision_id)
2657@@ -729,8 +722,7 @@
2658 recipe = self.factory.makeSourcePackageRecipe(
2659 branches=[self.db_branch])
2660 removeSecurityProxy(recipe).is_stale = False
2661- transaction.commit()
2662- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2663+ switch_dbuser(config.branchscanner.dbuser)
2664 self.makeBzrSync(self.db_branch).syncBranchAndClose()
2665 self.assertEqual(True, recipe.is_stale)
2666
2667@@ -740,8 +732,7 @@
2668 recipe = self.factory.makeSourcePackageRecipe(
2669 branches=[self.factory.makeBranch(), self.db_branch])
2670 removeSecurityProxy(recipe).is_stale = False
2671- transaction.commit()
2672- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2673+ switch_dbuser(config.branchscanner.dbuser)
2674 self.makeBzrSync(self.db_branch).syncBranchAndClose()
2675 self.assertEqual(True, recipe.is_stale)
2676
2677@@ -750,8 +741,7 @@
2678 """On tip unrelated recipes are left alone."""
2679 recipe = self.factory.makeSourcePackageRecipe()
2680 removeSecurityProxy(recipe).is_stale = False
2681- transaction.commit()
2682- LaunchpadZopelessLayer.switchDbUser(config.branchscanner.dbuser)
2683+ switch_dbuser(config.branchscanner.dbuser)
2684 self.makeBzrSync(self.db_branch).syncBranchAndClose()
2685 self.assertEqual(False, recipe.is_stale)
2686
2687
2688=== modified file 'lib/lp/codehosting/tests/test_branchdistro.py'
2689--- lib/lp/codehosting/tests/test_branchdistro.py 2012-01-01 02:58:52 +0000
2690+++ lib/lp/codehosting/tests/test_branchdistro.py 2012-01-24 12:44:15 +0000
2691@@ -42,6 +42,7 @@
2692 )
2693 from lp.services.osutils import override_environ
2694 from lp.testing import TestCaseWithFactory
2695+from lp.testing.dbuser import switch_dbuser
2696 from lp.testing.layers import LaunchpadZopelessLayer
2697
2698 # We say "RELEASE" often enough to not want to say "PackagePublishingPocket."
2699@@ -154,8 +155,7 @@
2700 self._log_file = StringIO()
2701 new_distroseries = self.factory.makeDistroSeries(
2702 distribution=distroseries.distribution)
2703- transaction.commit()
2704- self.layer.switchDbUser('branch-distro')
2705+ switch_dbuser('branch-distro')
2706 return DistroBrancher(
2707 FakeLogger(self._log_file), distroseries, new_distroseries)
2708
2709@@ -277,9 +277,8 @@
2710 self.assertIs(None, new_branch.stacked_on)
2711 self.assertEqual(new_branch, db_branch.stacked_on)
2712 # The script doesn't have permission to create branch jobs, but just
2713- # to be insanely paradoid.
2714- transaction.commit()
2715- self.layer.switchDbUser('launchpad')
2716+ # to be insanely paranoid.
2717+ switch_dbuser('launchpad')
2718 scan_jobs = list(getUtility(IBranchScanJobSource).iterReady())
2719 self.assertEqual(existing_scan_job_count, len(scan_jobs))
2720
2721@@ -450,12 +449,11 @@
2722 db_branch = self.makeOfficialPackageBranch()
2723 brancher = self.makeNewSeriesAndBrancher(db_branch.distroseries)
2724 new_db_branch = brancher.makeOneNewBranch(db_branch)
2725- self.layer.switchDbUser('launchpad')
2726+ switch_dbuser('launchpad')
2727 new_db_branch.setTarget(
2728 new_db_branch.owner,
2729 source_package=self.factory.makeSourcePackage())
2730- transaction.commit()
2731- self.layer.switchDbUser('branch-distro')
2732+ switch_dbuser('branch-distro')
2733 ok = brancher.checkOneBranch(new_db_branch)
2734 self.assertFalse(ok)
2735 self.assertLogMessages(
2736
2737=== modified file 'lib/lp/coop/answersbugs/tests/test_doc.py'
2738--- lib/lp/coop/answersbugs/tests/test_doc.py 2012-01-01 02:58:52 +0000
2739+++ lib/lp/coop/answersbugs/tests/test_doc.py 2012-01-24 12:44:15 +0000
2740@@ -23,6 +23,7 @@
2741 ANONYMOUS,
2742 login,
2743 )
2744+from lp.testing.dbuser import switch_dbuser
2745 from lp.testing.layers import (
2746 DatabaseFunctionalLayer,
2747 LaunchpadZopelessLayer,
2748@@ -82,7 +83,7 @@
2749
2750
2751 def uploaderBugLinkedToQuestionSetUp(test):
2752- LaunchpadZopelessLayer.switchDbUser('launchpad')
2753+ switch_dbuser('launchpad')
2754 bugLinkedToQuestionSetUp(test)
2755 LaunchpadZopelessLayer.commit()
2756 uploaderSetUp(test)
2757@@ -90,7 +91,7 @@
2758
2759
2760 def uploadQueueBugLinkedToQuestionSetUp(test):
2761- LaunchpadZopelessLayer.switchDbUser('launchpad')
2762+ switch_dbuser('launchpad')
2763 bugLinkedToQuestionSetUp(test)
2764 LaunchpadZopelessLayer.commit()
2765 uploadQueueSetUp(test)
2766
2767=== modified file 'lib/lp/hardwaredb/doc/hwdb-device-tables.txt'
2768--- lib/lp/hardwaredb/doc/hwdb-device-tables.txt 2011-12-28 17:03:06 +0000
2769+++ lib/lp/hardwaredb/doc/hwdb-device-tables.txt 2012-01-24 12:44:15 +0000
2770@@ -1036,7 +1036,12 @@
2771 Launchpad user, because the former has no access to the table
2772 distribution, which we want to access in this test.
2773
2774- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
2775+ >>> from lp.testing.dbuser import (
2776+ ... lp_dbuser,
2777+ ... switch_dbuser,
2778+ ... )
2779+
2780+ >>> switch_dbuser('launchpad')
2781 >>> sata_controller = device_set.getByDeviceID(
2782 ... bus=HWBus.PCI, vendor_id='0x10de', product_id='0x045d')
2783 >>> for submission in sata_controller.getSubmissions():
2784@@ -1120,7 +1125,7 @@
2785
2786 >>> import transaction
2787 >>> transaction.abort()
2788- >>> LaunchpadZopelessLayer.switchDbUser('hwdb-submission-processor')
2789+ >>> switch_dbuser('hwdb-submission-processor')
2790
2791 HWDevice.drivers is the set of drivers that are associated via
2792 HWDeviceDriverLink (see below) with this device.
2793@@ -1423,7 +1428,7 @@
2794 None
2795
2796 >>> transaction.abort()
2797- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
2798+ >>> switch_dbuser('launchpad')
2799
2800 We can search all the submissions related to a driver.
2801
2802@@ -1472,7 +1477,7 @@
2803 0
2804
2805 >>> transaction.abort()
2806- >>> LaunchpadZopelessLayer.switchDbUser('hwdb-submission-processor')
2807+ >>> switch_dbuser('hwdb-submission-processor')
2808
2809
2810 Driver names and package names
2811@@ -1482,7 +1487,7 @@
2812 HWDriverSet.all_driver_names() returns a list of distinct driver
2813 names used in the table HWDriver.
2814
2815- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
2816+ >>> switch_dbuser('launchpad')
2817 >>> for driver_name in driver_set.all_driver_names():
2818 ... print driver_name.name
2819 ahci
2820@@ -1510,7 +1515,7 @@
2821 linux-image-2.6.24-19-generic
2822 linux-image-generic
2823
2824- >>> LaunchpadZopelessLayer.switchDbUser('hwdb-submission-processor')
2825+ >>> switch_dbuser('hwdb-submission-processor')
2826
2827
2828 HWDeviceDriverLink
2829@@ -1715,13 +1720,13 @@
2830 IHWDevice.removeDeviceClass().
2831
2832 >>> LaunchpadZopelessLayer.txn.commit()
2833- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
2834+ >>> switch_dbuser('launchpad')
2835 >>> optic_pro_ut12.removeDeviceClass(main_class=0x07, sub_class=0x01)
2836 >>> for device_class in optic_pro_ut12.classes:
2837 ... print device_class.main_class, device_class.sub_class
2838 16 0
2839
2840- >>> LaunchpadZopelessLayer.switchDbUser('hwdb-submission-processor')
2841+ >>> switch_dbuser('hwdb-submission-processor')
2842
2843
2844 HWSubmissionDevice
2845@@ -1910,14 +1915,11 @@
2846 HWSubmissionDevice entries for the disk and the new submission, both
2847 for the "plain" disk and for the disk driven by the sd driver.
2848
2849- >>> LaunchpadZopelessLayer.txn.commit()
2850- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
2851- >>> # Set the emailaddress and hence the owner to a non-default
2852- >>> # value so that we have submissions with different owners.
2853- >>> submission = factory.makeHWSubmission(
2854- ... emailaddress='foo.bar@canonical.com')
2855- >>> LaunchpadZopelessLayer.txn.commit()
2856- >>> LaunchpadZopelessLayer.switchDbUser('hwdb-submission-processor')
2857+ >>> with lp_dbuser():
2858+ ... # Set the emailaddress and hence the owner to a non-default
2859+ ... # value so that we have submissions with different owners.
2860+ ... submission = factory.makeHWSubmission(
2861+ ... emailaddress='foo.bar@canonical.com')
2862 >>> first_device = factory.makeHWSubmissionDevice(
2863 ... submission, ide_disk, None, None, 1)
2864 >>> driver = getUtility(IHWDriverSet).getOrCreate(
2865@@ -1990,7 +1992,7 @@
2866 not counted here, because we created the new submission for a new
2867 distribution.
2868
2869- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
2870+ >>> switch_dbuser('launchpad')
2871 >>> print submission_device_set.numDevicesInSubmissions(
2872 ... bus=HWBus.IDE, vendor_id='SEAGATE', product_id='ST3250820NS ',
2873 ... distro_target=ubuntu)
2874@@ -2434,12 +2436,10 @@
2875
2876 >>> private_submission = factory.makeHWSubmission(
2877 ... emailaddress='no-priv@canonical.com', private=True)
2878- >>> LaunchpadZopelessLayer.txn.commit()
2879- >>> LaunchpadZopelessLayer.switchDbUser('hwdb-submission-processor')
2880+ >>> switch_dbuser('hwdb-submission-processor')
2881 >>> first_device = factory.makeHWSubmissionDevice(
2882 ... private_submission, ide_disk, None, None, 1)
2883- >>> LaunchpadZopelessLayer.txn.commit()
2884- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
2885+ >>> switch_dbuser('launchpad')
2886 >>> no_priv = getUtility(IPersonSet).getByEmail('no-priv@canonical.com')
2887 >>> bug_one.subscribe(no_priv, subscribed_by=no_priv)
2888 <lp.bugs.model.bugsubscription.BugSubscription ...>
2889
2890=== modified file 'lib/lp/hardwaredb/scripts/tests/test_hwdb_submission_processing.py'
2891--- lib/lp/hardwaredb/scripts/tests/test_hwdb_submission_processing.py 2011-12-30 01:48:17 +0000
2892+++ lib/lp/hardwaredb/scripts/tests/test_hwdb_submission_processing.py 2012-01-24 12:44:15 +0000
2893@@ -47,6 +47,7 @@
2894 TestCase,
2895 validate_mock_class,
2896 )
2897+from lp.testing.dbuser import switch_dbuser
2898 from lp.testing.layers import (
2899 BaseLayer,
2900 LaunchpadZopelessLayer,
2901@@ -4620,7 +4621,7 @@
2902 self.log.setLevel(logging.INFO)
2903 self.handler = Handler(self)
2904 self.handler.add(self.log.name)
2905- self.layer.switchDbUser('hwdb-submission-processor')
2906+ switch_dbuser('hwdb-submission-processor')
2907
2908 def getLogData(self):
2909 messages = [record.getMessage() for record in self.handler.records]
2910@@ -5079,7 +5080,7 @@
2911 """Create a submission."""
2912 if compress:
2913 data = bz2.compress(data)
2914- self.layer.switchDbUser('launchpad')
2915+ switch_dbuser('launchpad')
2916 submission = getUtility(IHWSubmissionSet).createSubmission(
2917 date_created=datetime(2007, 9, 9, tzinfo=pytz.timezone('UTC')),
2918 format=HWSubmissionFormat.VERSION_1,
2919@@ -5092,10 +5093,7 @@
2920 filename='hwinfo.xml',
2921 filesize=len(data),
2922 system_fingerprint='A Machine Name')
2923- # We want to access library file later: ensure that it is
2924- # properly stored.
2925- self.layer.txn.commit()
2926- self.layer.switchDbUser('hwdb-submission-processor')
2927+ switch_dbuser('hwdb-submission-processor')
2928 return submission
2929
2930 def getSampleData(self, filename):
2931
2932=== modified file 'lib/lp/hardwaredb/tests/test_doc.py'
2933--- lib/lp/hardwaredb/tests/test_doc.py 2012-01-01 02:58:52 +0000
2934+++ lib/lp/hardwaredb/tests/test_doc.py 2012-01-24 12:44:15 +0000
2935@@ -8,6 +8,7 @@
2936 import os
2937
2938 from lp.services.testing import build_test_suite
2939+from lp.testing.dbuser import switch_dbuser
2940 from lp.testing.layers import (
2941 LaunchpadFunctionalLayer,
2942 LaunchpadZopelessLayer,
2943@@ -24,7 +25,7 @@
2944
2945 def hwdbDeviceTablesSetup(test):
2946 setUp(test)
2947- LaunchpadZopelessLayer.switchDbUser('hwdb-submission-processor')
2948+ switch_dbuser('hwdb-submission-processor')
2949
2950
2951 special = {
2952
2953=== modified file 'lib/lp/registry/browser/tests/test_person_view.py'
2954--- lib/lp/registry/browser/tests/test_person_view.py 2012-01-05 00:23:45 +0000
2955+++ lib/lp/registry/browser/tests/test_person_view.py 2012-01-24 12:44:15 +0000
2956@@ -62,6 +62,7 @@
2957 StormStatementRecorder,
2958 TestCaseWithFactory,
2959 )
2960+from lp.testing.dbuser import switch_dbuser
2961 from lp.testing.layers import (
2962 DatabaseFunctionalLayer,
2963 LaunchpadFunctionalLayer,
2964@@ -205,10 +206,10 @@
2965
2966 In order to create the KarmaCache record we must switch to the DB
2967 user 'karma', so tests that need a different user after calling
2968- this method should do run switchDbUser() themselves.
2969+ this method should run switch_dbuser() themselves.
2970 """
2971
2972- LaunchpadZopelessLayer.switchDbUser('karma')
2973+ switch_dbuser('karma')
2974
2975 cache_manager = getUtility(IKarmaCacheManager)
2976 karmacache = cache_manager.new(
2977@@ -222,7 +223,7 @@
2978 value, person.id, category_id=None, product_id=product.id)
2979
2980 # We must commit here so that the change is seen in other transactions
2981- # (e.g. when the callsite issues a switchDbUser() after we return).
2982+ # (e.g. when the callsite issues a switch_dbuser() after we return).
2983 transaction.commit()
2984 return karmacache
2985
2986
2987=== modified file 'lib/lp/registry/doc/distribution-sourcepackage.txt'
2988--- lib/lp/registry/doc/distribution-sourcepackage.txt 2011-12-28 17:03:06 +0000
2989+++ lib/lp/registry/doc/distribution-sourcepackage.txt 2012-01-24 12:44:15 +0000
2990@@ -279,18 +279,15 @@
2991 # karma for their efforts.
2992 >>> ppa_beta_owner_id = ppa_beta.owner.id
2993 >>> ppa_nightly_owner_id = ppa_nightly.owner.id
2994- >>> transaction.commit()
2995
2996- >>> from lp.testing.layers import LaunchpadZopelessLayer
2997- >>> LaunchpadZopelessLayer.switchDbUser('karma')
2998+ >>> from lp.testing.dbuser import switch_dbuser
2999+ >>> switch_dbuser('karma')
3000 >>> from lp.registry.model.karma import KarmaTotalCache
3001 >>> cache_entry = KarmaTotalCache(person=ppa_beta_owner_id,
3002 ... karma_total=200)
3003 >>> cache_entry = KarmaTotalCache(person=ppa_nightly_owner_id,
3004 ... karma_total=201)
3005- >>> import transaction
3006- >>> transaction.commit()
3007- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
3008+ >>> switch_dbuser('launchpad')
3009
3010 The results of findRelatedArchives() are sorted so that archive containing
3011 the package created by the person with the greatest karma is first:
3012
3013=== modified file 'lib/lp/registry/doc/karmacache.txt'
3014--- lib/lp/registry/doc/karmacache.txt 2011-12-28 17:03:06 +0000
3015+++ lib/lp/registry/doc/karmacache.txt 2012-01-24 12:44:15 +0000
3016@@ -9,12 +9,12 @@
3017 which runs daily. The script does that by using the IKarmaCacheManager API.
3018
3019 >>> from zope.component import getUtility
3020- >>> from lp.testing.layers import LaunchpadZopelessLayer
3021+ >>> from lp.testing.dbuser import switch_dbuser
3022 >>> from lp.registry.interfaces.karma import IKarmaCacheManager
3023 >>> from lp.registry.interfaces.person import IPersonSet
3024 >>> from lp.registry.model.karma import KarmaCategory
3025
3026- >>> LaunchpadZopelessLayer.switchDbUser('karma')
3027+ >>> switch_dbuser('karma')
3028 >>> karmacachemanager = getUtility(IKarmaCacheManager)
3029
3030 == Creating new KarmaCache entries ==
3031
3032=== modified file 'lib/lp/registry/doc/standing.txt'
3033--- lib/lp/registry/doc/standing.txt 2011-12-30 06:14:56 +0000
3034+++ lib/lp/registry/doc/standing.txt 2012-01-24 12:44:15 +0000
3035@@ -54,6 +54,7 @@
3036 >>> from lp.registry.scripts.standing import (
3037 ... UpdatePersonalStanding)
3038 >>> from lp.services.config import config
3039+ >>> from lp.testing.dbuser import switch_dbuser
3040 >>> from lp.testing.layers import LaunchpadZopelessLayer
3041 >>> from lp.services.log.logger import DevNullLogger
3042 >>> class TestableScript(UpdatePersonalStanding):
3043@@ -63,16 +64,12 @@
3044 ... # Simulate Mailman acting changed state.
3045 ... flush_database_updates()
3046 ... mailinglists_helper.mailman.act()
3047- ... # Commit the in-progress transaction, since switching
3048- ... # database users does an abort.
3049- ... LaunchpadZopelessLayer.txn.commit()
3050 ... launchpad_dbuser = config.launchpad.dbuser
3051- ... LaunchpadZopelessLayer.switchDbUser(
3052- ... config.standingupdater.dbuser)
3053+ ... switch_dbuser(config.standingupdater.dbuser)
3054 ... self.txn = LaunchpadZopelessLayer.txn
3055 ... self.logger = DevNullLogger()
3056 ... results = super(TestableScript, self).main()
3057- ... LaunchpadZopelessLayer.switchDbUser(launchpad_dbuser)
3058+ ... switch_dbuser(launchpad_dbuser)
3059 ... return results
3060 >>> script = TestableScript('update-standing', test_args=[])
3061
3062
3063=== modified file 'lib/lp/registry/tests/test_distributionsourcepackage.py'
3064--- lib/lp/registry/tests/test_distributionsourcepackage.py 2011-12-30 06:14:56 +0000
3065+++ lib/lp/registry/tests/test_distributionsourcepackage.py 2012-01-24 12:44:15 +0000
3066@@ -25,6 +25,7 @@
3067 StormStatementRecorder,
3068 TestCaseWithFactory,
3069 )
3070+from lp.testing.dbuser import switch_dbuser
3071 from lp.testing.layers import (
3072 DatabaseFunctionalLayer,
3073 LaunchpadZopelessLayer,
3074@@ -203,14 +204,12 @@
3075 self.source_package = self.distribution.getSourcePackage('gedit')
3076
3077 # Add slightly more soyuz karma for person_nightly for this package.
3078- transaction.commit()
3079- self.layer.switchDbUser('karma')
3080+ switch_dbuser('karma')
3081 self.person_beta_karma = KarmaTotalCache(
3082 person=self.person_beta, karma_total=200)
3083 self.person_nightly_karma = KarmaTotalCache(
3084 person=self.person_nightly, karma_total=201)
3085- transaction.commit()
3086- self.layer.switchDbUser('launchpad')
3087+ switch_dbuser('launchpad')
3088
3089 def test_order_by_soyuz_package_karma(self):
3090 # Returned archives are ordered by the soyuz karma of the
3091@@ -227,10 +226,9 @@
3092
3093 # Update the soyuz karma for person_beta for this package so that
3094 # it is greater than person_nightly's.
3095- self.layer.switchDbUser('karma')
3096+ switch_dbuser('karma')
3097 self.person_beta_karma.karma_total = 202
3098- transaction.commit()
3099- self.layer.switchDbUser('launchpad')
3100+ switch_dbuser('launchpad')
3101
3102 related_archives = self.source_package.findRelatedArchives()
3103 related_archive_names = [
3104
3105=== modified file 'lib/lp/registry/tests/test_initderiveddistroseries.py'
3106--- lib/lp/registry/tests/test_initderiveddistroseries.py 2012-01-01 02:58:52 +0000
3107+++ lib/lp/registry/tests/test_initderiveddistroseries.py 2012-01-24 12:44:15 +0000
3108@@ -6,7 +6,6 @@
3109
3110 __metaclass__ = type
3111
3112-import transaction
3113 from zope.component import getUtility
3114 from zope.security.interfaces import Unauthorized
3115 from zope.security.proxy import removeSecurityProxy
3116@@ -28,6 +27,7 @@
3117 login_person,
3118 TestCaseWithFactory,
3119 )
3120+from lp.testing.dbuser import switch_dbuser
3121 from lp.testing.fakemethod import FakeMethod
3122 from lp.testing.layers import (
3123 LaunchpadFunctionalLayer,
3124@@ -103,8 +103,7 @@
3125 parent1, parent2 = self.setUpParents(
3126 packages1={'p1': '0.1-1'}, packages2={'p2': '2.1'})
3127 child = self.factory.makeDistroSeries()
3128- transaction.commit()
3129- self.layer.switchDbUser('initializedistroseries')
3130+ switch_dbuser('initializedistroseries')
3131
3132 child = self._fullInitialize(
3133 [parent1, parent2], child=child)
3134@@ -119,8 +118,7 @@
3135 parent1, parent2 = self.setUpParents(
3136 packages1={'p1': '0.1-1'}, packages2={'p2': '2.1'})
3137 child = self.factory.makeDistroSeries()
3138- transaction.commit()
3139- self.layer.switchDbUser('initializedistroseries')
3140+ switch_dbuser('initializedistroseries')
3141
3142 child = self._fullInitialize(
3143 [parent1, parent2], child=child)
3144@@ -130,7 +128,7 @@
3145 [(u'p1', u'0.1-1'), (u'p2', u'2.1')])
3146 # Switch back to launchpad_main to be able to cleanup the
3147 # feature flags.
3148- self.layer.switchDbUser('launchpad_main')
3149+ switch_dbuser('launchpad_main')
3150
3151 def test_multiple_parents_do_not_close_bugs(self):
3152 # The initialization does not close the bugs on the copied
3153@@ -139,8 +137,7 @@
3154 parent1, parent2 = self.setUpParents(
3155 packages1={'p1': '0.1-1'}, packages2={'p2': '2.1'})
3156 child = self.factory.makeDistroSeries()
3157- transaction.commit()
3158- self.layer.switchDbUser('initializedistroseries')
3159+ switch_dbuser('initializedistroseries')
3160
3161 # Patch close_bugs_for_sourcepublication to be able to record if
3162 # the method has been called.
3163@@ -164,7 +161,7 @@
3164 fakeCloseBugs.call_count)
3165 # Switch back to launchpad_main to be able to cleanup the
3166 # feature flags.
3167- self.layer.switchDbUser('launchpad_main')
3168+ switch_dbuser('launchpad_main')
3169
3170 def test_packageset_check_performed(self):
3171 # Packagesets passed to initDerivedDistroSeries are passed down
3172
3173=== modified file 'lib/lp/registry/tests/test_pillarname_triggers.py'
3174--- lib/lp/registry/tests/test_pillarname_triggers.py 2011-12-30 06:14:56 +0000
3175+++ lib/lp/registry/tests/test_pillarname_triggers.py 2012-01-24 12:44:15 +0000
3176@@ -9,6 +9,7 @@
3177 import unittest
3178
3179 from lp.services.database.sqlbase import cursor
3180+from lp.testing.dbuser import switch_dbuser
3181 from lp.testing.layers import LaunchpadZopelessLayer
3182
3183
3184@@ -16,7 +17,7 @@
3185 layer = LaunchpadZopelessLayer
3186
3187 def setUp(self):
3188- LaunchpadZopelessLayer.switchDbUser('testadmin')
3189+ switch_dbuser('testadmin')
3190
3191 def testDistributionTable(self):
3192 cur = cursor()
3193
3194=== modified file 'lib/lp/registry/tests/test_prf_finder.py'
3195--- lib/lp/registry/tests/test_prf_finder.py 2012-01-01 02:58:52 +0000
3196+++ lib/lp/registry/tests/test_prf_finder.py 2012-01-24 12:44:15 +0000
3197@@ -28,6 +28,7 @@
3198 reset_logging,
3199 TestCaseWithFactory,
3200 )
3201+from lp.testing.dbuser import switch_dbuser
3202 from lp.testing.layers import LaunchpadZopelessLayer
3203
3204
3205@@ -193,8 +194,7 @@
3206 return file_path, file_name
3207
3208 def setUp(self):
3209- LaunchpadZopelessLayer.switchDbUser(
3210- config.productreleasefinder.dbuser)
3211+ switch_dbuser(config.productreleasefinder.dbuser)
3212 self.release_root = tempfile.mkdtemp()
3213 self.release_url = 'file://' + self.release_root
3214
3215
3216=== modified file 'lib/lp/registry/tests/test_ro_user.py'
3217--- lib/lp/registry/tests/test_ro_user.py 2011-12-30 06:14:56 +0000
3218+++ lib/lp/registry/tests/test_ro_user.py 2012-01-24 12:44:15 +0000
3219@@ -10,6 +10,7 @@
3220 import psycopg2
3221
3222 from lp.services.database.sqlbase import cursor
3223+from lp.testing.dbuser import switch_dbuser
3224 from lp.testing.layers import LaunchpadZopelessLayer
3225
3226
3227@@ -18,7 +19,7 @@
3228 layer = LaunchpadZopelessLayer
3229
3230 def setUp(self):
3231- self.layer.switchDbUser('ro')
3232+ switch_dbuser('ro')
3233
3234 def test(self):
3235 """Test that read-only users cannot make changes to the database."""
3236
3237=== modified file 'lib/lp/registry/tests/test_teammembership.py'
3238--- lib/lp/registry/tests/test_teammembership.py 2011-12-30 06:14:56 +0000
3239+++ lib/lp/registry/tests/test_teammembership.py 2012-01-24 12:44:15 +0000
3240@@ -81,7 +81,7 @@
3241 class TestTeamMembershipSetScripts(TestCaseWithFactory):
3242 """Separate Testcase to separate out examples required dbuser switches.
3243
3244- This uses the LaunchpadZoplelessLayer to provide layer.switchDbUser
3245+ This uses the LaunchpadZopelessLayer to provide switch_dbuser.
3246 """
3247
3248 layer = LaunchpadZopelessLayer
3249
3250=== modified file 'lib/lp/scripts/tests/test_garbo.py'
3251--- lib/lp/scripts/tests/test_garbo.py 2012-01-13 16:23:10 +0000
3252+++ lib/lp/scripts/tests/test_garbo.py 2012-01-24 12:44:15 +0000
3253@@ -101,6 +101,7 @@
3254 TestCase,
3255 TestCaseWithFactory,
3256 )
3257+from lp.testing.dbuser import switch_dbuser
3258 from lp.testing.layers import (
3259 DatabaseLayer,
3260 LaunchpadScriptLayer,
3261@@ -383,8 +384,7 @@
3262 self.log.addHandler(handler)
3263
3264 def runFrequently(self, maximum_chunk_size=2, test_args=()):
3265- transaction.commit()
3266- LaunchpadZopelessLayer.switchDbUser('garbo_daily')
3267+ switch_dbuser('garbo_daily')
3268 collector = FrequentDatabaseGarbageCollector(
3269 test_args=list(test_args))
3270 collector._maximum_chunk_size = maximum_chunk_size
3271@@ -393,8 +393,7 @@
3272 return collector
3273
3274 def runDaily(self, maximum_chunk_size=2, test_args=()):
3275- transaction.commit()
3276- LaunchpadZopelessLayer.switchDbUser('garbo_daily')
3277+ switch_dbuser('garbo_daily')
3278 collector = DailyDatabaseGarbageCollector(test_args=list(test_args))
3279 collector._maximum_chunk_size = maximum_chunk_size
3280 collector.logger = self.log
3281@@ -402,7 +401,7 @@
3282 return collector
3283
3284 def runHourly(self, maximum_chunk_size=2, test_args=()):
3285- LaunchpadZopelessLayer.switchDbUser('garbo_hourly')
3286+ switch_dbuser('garbo_hourly')
3287 collector = HourlyDatabaseGarbageCollector(test_args=list(test_args))
3288 collector._maximum_chunk_size = maximum_chunk_size
3289 collector.logger = self.log
3290@@ -417,7 +416,7 @@
3291 now - timedelta(days=1) + timedelta(seconds=60), # Not garbage
3292 now, # Not garbage
3293 ]
3294- LaunchpadZopelessLayer.switchDbUser('testadmin')
3295+ switch_dbuser('testadmin')
3296 store = IMasterStore(OAuthNonce)
3297
3298 # Make sure we start with 0 nonces.
3299@@ -461,7 +460,7 @@
3300 now - 1 * DAYS + 1 * MINUTES, # Not garbage
3301 now, # Not garbage
3302 ]
3303- LaunchpadZopelessLayer.switchDbUser('testadmin')
3304+ switch_dbuser('testadmin')
3305
3306 store = IMasterStore(OpenIDConsumerNonce)
3307
3308@@ -496,14 +495,14 @@
3309 results_to_keep_count = (
3310 config.codeimport.consecutive_failure_limit - 1)
3311
3312- LaunchpadZopelessLayer.switchDbUser('testadmin')
3313+ switch_dbuser('testadmin')
3314 code_import_id = self.factory.makeCodeImport().id
3315 machine_id = self.factory.makeCodeImportMachine().id
3316 requester_id = self.factory.makePerson().id
3317 transaction.commit()
3318
3319 def new_code_import_result(timestamp):
3320- LaunchpadZopelessLayer.switchDbUser('testadmin')
3321+ switch_dbuser('testadmin')
3322 CodeImportResult(
3323 date_created=timestamp,
3324 code_importID=code_import_id, machineID=machine_id,
3325@@ -550,7 +549,7 @@
3326 now = datetime.now(UTC)
3327 store = IMasterStore(CodeImportResult)
3328
3329- LaunchpadZopelessLayer.switchDbUser('testadmin')
3330+ switch_dbuser('testadmin')
3331 machine = self.factory.makeCodeImportMachine()
3332 requester = self.factory.makePerson()
3333 # Create 6 code import events for this machine, 3 on each side of 30
3334@@ -578,7 +577,7 @@
3335 def test_OpenIDConsumerAssociationPruner(self):
3336 pruner = OpenIDConsumerAssociationPruner
3337 table_name = pruner.table_name
3338- LaunchpadZopelessLayer.switchDbUser('testadmin')
3339+ switch_dbuser('testadmin')
3340 store_selector = getUtility(IStoreSelector)
3341 store = store_selector.get(MAIN_STORE, MASTER_FLAVOR)
3342 now = time.time()
3343@@ -602,7 +601,7 @@
3344 # test is running slow.
3345 self.runFrequently()
3346
3347- LaunchpadZopelessLayer.switchDbUser('testadmin')
3348+ switch_dbuser('testadmin')
3349 store = store_selector.get(MAIN_STORE, MASTER_FLAVOR)
3350 # Confirm all the rows we know should have been expired have
3351 # been expired. These are the ones that would be expired using
3352@@ -620,7 +619,7 @@
3353 self.failUnless(num_unexpired > 0)
3354
3355 def test_RevisionAuthorEmailLinker(self):
3356- LaunchpadZopelessLayer.switchDbUser('testadmin')
3357+ switch_dbuser('testadmin')
3358 rev1 = self.factory.makeRevision('Author 1 <author-1@Example.Org>')
3359 rev2 = self.factory.makeRevision('Author 2 <author-2@Example.Org>')
3360
3361@@ -636,7 +635,7 @@
3362
3363 # Only the validated email address associated with a Person
3364 # causes a linkage.
3365- LaunchpadZopelessLayer.switchDbUser('testadmin')
3366+ switch_dbuser('testadmin')
3367 self.assertEqual(rev1.revision_author.person, person1)
3368 self.assertEqual(rev2.revision_author.person, None)
3369
3370@@ -645,11 +644,11 @@
3371 self.assertEqual(rev2.revision_author.person, None)
3372
3373 self.runDaily()
3374- LaunchpadZopelessLayer.switchDbUser('testadmin')
3375+ switch_dbuser('testadmin')
3376 self.assertEqual(rev2.revision_author.person, person2)
3377
3378 def test_HWSubmissionEmailLinker(self):
3379- LaunchpadZopelessLayer.switchDbUser('testadmin')
3380+ switch_dbuser('testadmin')
3381 sub1 = self.factory.makeHWSubmission(
3382 emailaddress='author-1@Example.Org')
3383 sub2 = self.factory.makeHWSubmission(
3384@@ -667,7 +666,7 @@
3385
3386 # Only the validated email address associated with a Person
3387 # causes a linkage.
3388- LaunchpadZopelessLayer.switchDbUser('testadmin')
3389+ switch_dbuser('testadmin')
3390 self.assertEqual(sub1.owner, person1)
3391 self.assertEqual(sub2.owner, None)
3392
3393@@ -676,14 +675,14 @@
3394 self.assertEqual(sub2.owner, None)
3395
3396 self.runDaily()
3397- LaunchpadZopelessLayer.switchDbUser('testadmin')
3398+ switch_dbuser('testadmin')
3399 self.assertEqual(sub2.owner, person2)
3400
3401 def test_PersonPruner(self):
3402 personset = getUtility(IPersonSet)
3403 # Switch the DB user because the garbo_daily user isn't allowed to
3404 # create person entries.
3405- LaunchpadZopelessLayer.switchDbUser('testadmin')
3406+ switch_dbuser('testadmin')
3407
3408 # Create two new person entries, both not linked to anything. One of
3409 # them will have the present day as its date created, and so will not
3410@@ -711,7 +710,7 @@
3411
3412 def test_BugNotificationPruner(self):
3413 # Create some sample data
3414- LaunchpadZopelessLayer.switchDbUser('testadmin')
3415+ switch_dbuser('testadmin')
3416 notification = BugNotification(
3417 messageID=1,
3418 bugID=1,
3419@@ -777,7 +776,7 @@
3420 def _test_AnswerContactPruner(self, status, interval, expected_count=0):
3421 # Garbo should remove answer contacts for accounts with given 'status'
3422 # which was set more than 'interval' days ago.
3423- LaunchpadZopelessLayer.switchDbUser('testadmin')
3424+ switch_dbuser('testadmin')
3425 store = IMasterStore(AnswerContact)
3426
3427 person = self.factory.makePerson()
3428@@ -802,7 +801,7 @@
3429
3430 self.runDaily()
3431
3432- LaunchpadZopelessLayer.switchDbUser('testadmin')
3433+ switch_dbuser('testadmin')
3434 self.assertEqual(
3435 store.find(
3436 AnswerContact,
3437@@ -830,7 +829,7 @@
3438
3439 def test_BranchJobPruner(self):
3440 # Garbo should remove jobs completed over 30 days ago.
3441- LaunchpadZopelessLayer.switchDbUser('testadmin')
3442+ switch_dbuser('testadmin')
3443 store = IMasterStore(Job)
3444
3445 db_branch = self.factory.makeAnyBranch()
3446@@ -849,7 +848,7 @@
3447
3448 self.runDaily()
3449
3450- LaunchpadZopelessLayer.switchDbUser('testadmin')
3451+ switch_dbuser('testadmin')
3452 self.assertEqual(
3453 store.find(
3454 BranchJob,
3455@@ -859,7 +858,7 @@
3456 def test_BranchJobPruner_doesnt_prune_recent_jobs(self):
3457 # Check to make sure the garbo doesn't remove jobs that aren't more
3458 # than thirty days old.
3459- LaunchpadZopelessLayer.switchDbUser('testadmin')
3460+ switch_dbuser('testadmin')
3461 store = IMasterStore(Job)
3462
3463 db_branch = self.factory.makeAnyBranch(
3464@@ -877,13 +876,13 @@
3465
3466 self.runDaily()
3467
3468- LaunchpadZopelessLayer.switchDbUser('testadmin')
3469+ switch_dbuser('testadmin')
3470 self.assertEqual(store.find(BranchJob).count(), 1)
3471
3472 def test_ObsoleteBugAttachmentPruner(self):
3473 # Bug attachments without a LibraryFileContent record are removed.
3474
3475- LaunchpadZopelessLayer.switchDbUser('testadmin')
3476+ switch_dbuser('testadmin')
3477 bug = self.factory.makeBug()
3478 attachment = self.factory.makeBugAttachment(bug=bug)
3479 transaction.commit()
3480@@ -896,11 +895,11 @@
3481
3482 # But once we delete the LfC record, the attachment is deleted
3483 # in the next daily garbo run.
3484- LaunchpadZopelessLayer.switchDbUser('testadmin')
3485+ switch_dbuser('testadmin')
3486 removeSecurityProxy(attachment.libraryfile).content = None
3487 transaction.commit()
3488 self.runDaily()
3489- LaunchpadZopelessLayer.switchDbUser('testadmin')
3490+ switch_dbuser('testadmin')
3491 self.assertEqual(bug.attachments.count(), 0)
3492
3493 def test_TimeLimitedTokenPruner(self):
3494@@ -924,7 +923,7 @@
3495 path="sample path", token="bar"))))
3496
3497 def test_CacheSuggestivePOTemplates(self):
3498- LaunchpadZopelessLayer.switchDbUser('testadmin')
3499+ switch_dbuser('testadmin')
3500 template = self.factory.makePOTemplate()
3501 self.runDaily()
3502
3503@@ -938,7 +937,7 @@
3504 self.assertEqual(1, count)
3505
3506 def test_BugSummaryJournalRollup(self):
3507- LaunchpadZopelessLayer.switchDbUser('testadmin')
3508+ switch_dbuser('testadmin')
3509 store = getUtility(IStoreSelector).get(MAIN_STORE, MASTER_FLAVOR)
3510
3511 # Generate a load of entries in BugSummaryJournal.
3512@@ -960,7 +959,7 @@
3513 def test_UnusedPOTMsgSetPruner_removes_obsolete_message_sets(self):
3514 # UnusedPOTMsgSetPruner removes any POTMsgSet that are
3515 # participating in a POTemplate only as obsolete messages.
3516- LaunchpadZopelessLayer.switchDbUser('testadmin')
3517+ switch_dbuser('testadmin')
3518 pofile = self.factory.makePOFile()
3519 translation_message = self.factory.makeCurrentTranslationMessage(
3520 pofile=pofile)
3521@@ -979,7 +978,7 @@
3522 def test_UnusedPOTMsgSetPruner_removes_unreferenced_message_sets(self):
3523 # If a POTMsgSet is not referenced by any templates the
3524 # UnusedPOTMsgSetPruner will remove it.
3525- LaunchpadZopelessLayer.switchDbUser('testadmin')
3526+ switch_dbuser('testadmin')
3527 potmsgset = self.factory.makePOTMsgSet()
3528 # Cheekily drop any references to the POTMsgSet we just created.
3529 store = IMasterStore(POTMsgSet)
3530@@ -1003,7 +1002,7 @@
3531 def test_LoginTokenPruner(self):
3532 store = IMasterStore(LoginToken)
3533 now = datetime.now(UTC)
3534- LaunchpadZopelessLayer.switchDbUser('testadmin')
3535+ switch_dbuser('testadmin')
3536
3537 # It is configured as a daily task.
3538 self.assertTrue(
3539@@ -1024,7 +1023,7 @@
3540
3541 # Run the pruner. Batching is tested by the BulkPruner tests so
3542 # no need to repeat here.
3543- LaunchpadZopelessLayer.switchDbUser('garbo_daily')
3544+ switch_dbuser('garbo_daily')
3545 pruner = LoginTokenPruner(logging.getLogger('garbo'))
3546 while not pruner.isDone():
3547 pruner(10)
3548
3549=== modified file 'lib/lp/services/apachelogparser/tests/test_apachelogparser.py'
3550--- lib/lp/services/apachelogparser/tests/test_apachelogparser.py 2011-12-30 01:04:24 +0000
3551+++ lib/lp/services/apachelogparser/tests/test_apachelogparser.py 2012-01-24 12:44:15 +0000
3552@@ -29,6 +29,7 @@
3553 MAIN_STORE,
3554 )
3555 from lp.testing import TestCase
3556+from lp.testing.dbuser import switch_dbuser
3557 from lp.testing.layers import (
3558 LaunchpadZopelessLayer,
3559 ZopelessLayer,
3560@@ -388,7 +389,7 @@
3561
3562 def setUp(self):
3563 super(TestParsedFilesDetection, self).setUp()
3564- self.layer.switchDbUser(DBUSER)
3565+ switch_dbuser(DBUSER)
3566
3567 def test_not_parsed_file(self):
3568 # A file that has never been parsed will have to be parsed from the
3569@@ -470,7 +471,7 @@
3570
3571 def setUp(self):
3572 super(Test_create_or_update_parsedlog_entry, self).setUp()
3573- self.layer.switchDbUser(DBUSER)
3574+ switch_dbuser(DBUSER)
3575
3576 def test_creation_of_new_entries(self):
3577 # When given a first_line that doesn't exist in the ParsedApacheLog
3578
3579=== modified file 'lib/lp/services/database/tests/test_transaction_decorators.py'
3580--- lib/lp/services/database/tests/test_transaction_decorators.py 2011-12-30 01:48:17 +0000
3581+++ lib/lp/services/database/tests/test_transaction_decorators.py 2012-01-24 12:44:15 +0000
3582@@ -17,6 +17,7 @@
3583 IStoreSelector,
3584 MAIN_STORE,
3585 )
3586+from lp.testing.dbuser import switch_dbuser
3587 from lp.testing.layers import LaunchpadZopelessLayer
3588
3589
3590@@ -26,7 +27,7 @@
3591 layer = LaunchpadZopelessLayer
3592
3593 def setUp(self):
3594- self.layer.switchDbUser('librarian')
3595+ switch_dbuser('librarian')
3596 self.store = getUtility(IStoreSelector).get(
3597 MAIN_STORE, DEFAULT_FLAVOR)
3598 self.content_id = db.Library().add('deadbeef', 1234, 'abababab')
3599
3600=== modified file 'lib/lp/services/librarianserver/tests/test_db.py'
3601--- lib/lp/services/librarianserver/tests/test_db.py 2011-12-30 02:19:42 +0000
3602+++ lib/lp/services/librarianserver/tests/test_db.py 2012-01-24 12:44:15 +0000
3603@@ -13,6 +13,7 @@
3604 IStoreSelector,
3605 MAIN_STORE,
3606 )
3607+from lp.testing.dbuser import switch_dbuser
3608 from lp.testing.layers import LaunchpadZopelessLayer
3609
3610
3611@@ -20,7 +21,7 @@
3612 layer = LaunchpadZopelessLayer
3613
3614 def setUp(self):
3615- self.layer.switchDbUser('librarian')
3616+ switch_dbuser('librarian')
3617
3618 def test_lookupByDigest(self):
3619 # Create library
3620@@ -53,7 +54,7 @@
3621 layer = LaunchpadZopelessLayer
3622
3623 def setUp(self):
3624- self.layer.switchDbUser('librarian')
3625+ switch_dbuser('librarian')
3626 self.store = getUtility(IStoreSelector).get(
3627 MAIN_STORE, DEFAULT_FLAVOR)
3628 self.content_id = db.Library().add('deadbeef', 1234, 'abababab')
3629
3630=== modified file 'lib/lp/services/librarianserver/tests/test_gc.py'
3631--- lib/lp/services/librarianserver/tests/test_gc.py 2011-12-30 06:14:56 +0000
3632+++ lib/lp/services/librarianserver/tests/test_gc.py 2012-01-24 12:44:15 +0000
3633@@ -35,6 +35,7 @@
3634 from lp.services.log.logger import BufferLogger
3635 from lp.services.utils import utc_now
3636 from lp.testing import TestCase
3637+from lp.testing.dbuser import switch_dbuser
3638 from lp.testing.layers import LaunchpadZopelessLayer
3639
3640
3641@@ -61,7 +62,7 @@
3642
3643 self.f1_id, self.f2_id = self._makeDupes()
3644
3645- self.layer.switchDbUser(config.librarian_gc.dbuser)
3646+ switch_dbuser(config.librarian_gc.dbuser)
3647 self.ztm = self.layer.txn
3648
3649 # Make sure the files exist. We do this in setup, because we
3650@@ -102,7 +103,7 @@
3651 # Connect to the database as a user with file upload privileges,
3652 # in this case the PostgreSQL default user who happens to be an
3653 # administrator on launchpad development boxes.
3654- self.layer.switchDbUser(dbuser='testadmin')
3655+ switch_dbuser('testadmin')
3656 ztm = self.layer.txn
3657
3658 ztm.begin()
3659@@ -542,14 +543,14 @@
3660 def test_delete_unwanted_files_bug437084(self):
3661 # There was a bug where delete_unwanted_files() would die
3662 # if the last file found on disk was unwanted.
3663- self.layer.switchDbUser(dbuser='testadmin')
3664+ switch_dbuser('testadmin')
3665 content = 'foo'
3666 self.client.addFile(
3667 'foo.txt', len(content), StringIO(content), 'text/plain')
3668 # Roll back the database changes, leaving the file on disk.
3669 transaction.abort()
3670
3671- self.layer.switchDbUser(config.librarian_gc.dbuser)
3672+ switch_dbuser(config.librarian_gc.dbuser)
3673
3674 # This should cope.
3675 librariangc.delete_unwanted_files(self.con)
3676@@ -558,14 +559,14 @@
3677 # In production, our tree has symlinks in it now. We need to be able
3678 # to cope.
3679 # First, let's make sure we have some trash.
3680- self.layer.switchDbUser(dbuser='testadmin')
3681+ switch_dbuser('testadmin')
3682 content = 'foo'
3683 self.client.addFile(
3684 'foo.txt', len(content), StringIO(content), 'text/plain')
3685 # Roll back the database changes, leaving the file on disk.
3686 transaction.abort()
3687
3688- self.layer.switchDbUser(config.librarian_gc.dbuser)
3689+ switch_dbuser(config.librarian_gc.dbuser)
3690
3691 # Now, we will move the directory containing the trash somewhere else
3692 # and make a symlink to it.
3693@@ -752,7 +753,7 @@
3694 open(path, 'w').write('whatever')
3695 self.layer.txn.abort()
3696
3697- self.layer.switchDbUser(config.librarian_gc.dbuser)
3698+ switch_dbuser(config.librarian_gc.dbuser)
3699
3700 # Open a connection for our test
3701 self.con = connect(
3702
3703=== modified file 'lib/lp/services/librarianserver/tests/test_storage_db.py'
3704--- lib/lp/services/librarianserver/tests/test_storage_db.py 2011-12-30 06:14:56 +0000
3705+++ lib/lp/services/librarianserver/tests/test_storage_db.py 2012-01-24 12:44:15 +0000
3706@@ -15,6 +15,7 @@
3707 LibrarianStorage,
3708 LibraryFileUpload,
3709 )
3710+from lp.testing.dbuser import switch_dbuser
3711 from lp.testing.layers import LaunchpadZopelessLayer
3712
3713
3714@@ -22,7 +23,7 @@
3715 layer = LaunchpadZopelessLayer
3716
3717 def setUp(self):
3718- self.layer.switchDbUser('librarian')
3719+ switch_dbuser('librarian')
3720 self.directory = tempfile.mkdtemp()
3721 self.storage = LibrarianStorage(self.directory, db.Library())
3722
3723
3724=== modified file 'lib/lp/services/librarianserver/tests/test_web.py'
3725--- lib/lp/services/librarianserver/tests/test_web.py 2011-12-30 06:14:56 +0000
3726+++ lib/lp/services/librarianserver/tests/test_web.py 2012-01-24 12:44:15 +0000
3727@@ -34,6 +34,7 @@
3728 LibraryFileAlias,
3729 TimeLimitedToken,
3730 )
3731+from lp.testing.dbuser import switch_dbuser
3732 from lp.testing.layers import (
3733 LaunchpadFunctionalLayer,
3734 LaunchpadZopelessLayer,
3735@@ -380,7 +381,7 @@
3736 layer = LaunchpadZopelessLayer
3737
3738 def setUp(self):
3739- LaunchpadZopelessLayer.switchDbUser(config.librarian.dbuser)
3740+ switch_dbuser(config.librarian.dbuser)
3741
3742 def commit(self):
3743 LaunchpadZopelessLayer.commit()
3744@@ -440,20 +441,18 @@
3745 layer = LaunchpadZopelessLayer
3746
3747 def setUp(self):
3748- LaunchpadZopelessLayer.switchDbUser(config.librarian.dbuser)
3749+ switch_dbuser(config.librarian.dbuser)
3750
3751 def test_deletedContentNotFound(self):
3752 # Use a user with rights to change the deleted flag in the db.
3753 # This currently means a superuser.
3754- LaunchpadZopelessLayer.switchDbUser('testadmin')
3755+ switch_dbuser('testadmin')
3756
3757 alias = getUtility(ILibraryFileAliasSet).create(
3758 'whatever', 8, StringIO('xxx\nxxx\n'), 'text/plain')
3759 alias_id = alias.id
3760 transaction.commit()
3761
3762- client = LibrarianClient()
3763-
3764 # This works
3765 alias = getUtility(ILibraryFileAliasSet)[alias_id]
3766 alias.open()
3767@@ -465,7 +464,6 @@
3768 retrieved_content = urlopen(url).read()
3769 self.failUnlessEqual(retrieved_content, 'xxx\nxxx\n')
3770
3771-
3772 # But when we flag the content as deleted
3773 cur = cursor()
3774 cur.execute("""
3775
3776=== modified file 'lib/lp/services/mail/doc/emailauthentication.txt'
3777--- lib/lp/services/mail/doc/emailauthentication.txt 2011-12-30 06:14:56 +0000
3778+++ lib/lp/services/mail/doc/emailauthentication.txt 2012-01-24 12:44:15 +0000
3779@@ -10,15 +10,11 @@
3780 signature. First we have to import the OpenPGP keys we will use in the
3781 emails:
3782
3783- >>> from lp.services.config import config
3784- >>> from lp.services.database.sqlbase import commit
3785- >>> from lp.testing.layers import LaunchpadZopelessLayer
3786+ >>> from lp.testing.dbuser import lp_dbuser
3787 >>> from lp.testing.gpgkeys import import_public_test_keys
3788
3789- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
3790- >>> import_public_test_keys()
3791- >>> commit()
3792- >>> LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
3793+ >>> with lp_dbuser():
3794+ ... import_public_test_keys()
3795
3796 For most of these tests, we don't care whether the timestamps are out of
3797 date:
3798
3799=== modified file 'lib/lp/services/mail/tests/incomingmail.txt'
3800--- lib/lp/services/mail/tests/incomingmail.txt 2011-12-30 06:14:56 +0000
3801+++ lib/lp/services/mail/tests/incomingmail.txt 2012-01-24 12:44:15 +0000
3802@@ -45,10 +45,9 @@
3803
3804 Now we send a few test mails to foo.com, bar.com, and baz.com:
3805
3806- >>> from lp.services.database.sqlbase import commit
3807 >>> from lp.services.mail.tests.helpers import read_test_message
3808- >>> from lp.testing.layers import LaunchpadZopelessLayer
3809 >>> from lp.services.mail.sendmail import sendmail as original_sendmail
3810+ >>> from lp.testing.dbuser import switch_dbuser
3811
3812 For these examples, we don't want the Precedence header added. Domains
3813 are treated without regard to case: for incoming mail, foo.com and
3814@@ -57,7 +56,7 @@
3815 >>> def sendmail(msg, to_addrs=None):
3816 ... return original_sendmail(msg, to_addrs=to_addrs, bulk=False)
3817
3818- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
3819+ >>> switch_dbuser('launchpad')
3820 >>> msgids = {'foo.com': [], 'bar.com': [], 'baz.com': []}
3821 >>> for domain in ('foo.com', 'bar.com', 'FOO.COM', 'baz.com'):
3822 ... msg = read_test_message('signed_detached.txt')
3823@@ -75,9 +74,10 @@
3824
3825 >>> from lp.services.config import config
3826 >>> from lp.testing.gpgkeys import import_public_test_keys
3827+ >>> from lp.testing.layers import LaunchpadZopelessLayer
3828+
3829 >>> import_public_test_keys()
3830- >>> commit()
3831- >>> LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
3832+ >>> switch_dbuser(config.processmail.dbuser)
3833 >>> zopeless_transaction = LaunchpadZopelessLayer.txn
3834
3835 >>> handleMailForTest = lambda: handleMail(
3836
3837=== modified file 'lib/lp/services/mail/tests/test_doc.py'
3838--- lib/lp/services/mail/tests/test_doc.py 2012-01-01 02:58:52 +0000
3839+++ lib/lp/services/mail/tests/test_doc.py 2012-01-24 12:44:15 +0000
3840@@ -12,6 +12,7 @@
3841 from lp.services.config import config
3842 from lp.services.testing import build_test_suite
3843 from lp.services.webapp.authorization import LaunchpadSecurityPolicy
3844+from lp.testing.dbuser import switch_dbuser
3845 from lp.testing.layers import (
3846 DatabaseFunctionalLayer,
3847 LaunchpadZopelessLayer,
3848@@ -37,7 +38,7 @@
3849 connects as a specific DB user.
3850 """
3851 cls._old_policy = setSecurityPolicy(LaunchpadSecurityPolicy)
3852- LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
3853+ switch_dbuser(config.processmail.dbuser)
3854
3855 @classmethod
3856 def testTearDown(cls):
3857
3858=== modified file 'lib/lp/services/mail/tests/test_incoming.py'
3859--- lib/lp/services/mail/tests/test_incoming.py 2012-01-04 03:23:19 +0000
3860+++ lib/lp/services/mail/tests/test_incoming.py 2012-01-24 12:44:15 +0000
3861@@ -27,6 +27,7 @@
3862 from lp.services.mail.tests.helpers import testmails_path
3863 from lp.services.webapp.authorization import LaunchpadSecurityPolicy
3864 from lp.testing import TestCaseWithFactory
3865+from lp.testing.dbuser import switch_dbuser
3866 from lp.testing.factory import GPGSigningContext
3867 from lp.testing.gpgkeys import import_secret_test_key
3868 from lp.testing.layers import LaunchpadZopelessLayer
3869@@ -147,7 +148,7 @@
3870
3871 def setUp(test):
3872 test._old_policy = setSecurityPolicy(LaunchpadSecurityPolicy)
3873- LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
3874+ switch_dbuser(config.processmail.dbuser)
3875
3876
3877 def tearDown(test):
3878
3879=== modified file 'lib/lp/services/scripts/doc/script-monitoring.txt'
3880--- lib/lp/services/scripts/doc/script-monitoring.txt 2011-12-28 17:03:06 +0000
3881+++ lib/lp/services/scripts/doc/script-monitoring.txt 2012-01-24 12:44:15 +0000
3882@@ -25,10 +25,10 @@
3883 >>> from zope.component import getUtility
3884 >>> from lp.services.scripts.interfaces.scriptactivity import (
3885 ... IScriptActivitySet)
3886- >>> from lp.testing.layers import LaunchpadZopelessLayer
3887+ >>> from lp.testing.dbuser import switch_dbuser
3888
3889 >>> UTC = pytz.timezone('UTC')
3890- >>> LaunchpadZopelessLayer.switchDbUser('garbo_daily') # A script db user
3891+ >>> switch_dbuser('garbo_daily') # A script db user
3892
3893 >>> activity = getUtility(IScriptActivitySet).recordSuccess(
3894 ... name='script-name',
3895
3896=== modified file 'lib/lp/services/statistics/tests/test_update_stats.py'
3897--- lib/lp/services/statistics/tests/test_update_stats.py 2011-12-30 06:14:56 +0000
3898+++ lib/lp/services/statistics/tests/test_update_stats.py 2012-01-24 12:44:15 +0000
3899@@ -17,6 +17,7 @@
3900 from lp.services.config import config
3901 from lp.services.database.sqlbase import cursor
3902 from lp.services.worlddata.interfaces.language import ILanguageSet
3903+from lp.testing.dbuser import switch_dbuser
3904 from lp.testing.layers import LaunchpadZopelessLayer
3905 from lp.translations.interfaces.potemplate import IPOTemplateSet
3906
3907@@ -33,7 +34,7 @@
3908 layer = LaunchpadZopelessLayer
3909
3910 def setUp(self):
3911- self.layer.switchDbUser('statistician')
3912+ switch_dbuser('statistician')
3913
3914 def tearDown(self):
3915 # Test uses a subprocess, so force the database to be dirty
3916
3917=== modified file 'lib/lp/services/worlddata/doc/language.txt'
3918--- lib/lp/services/worlddata/doc/language.txt 2011-12-28 17:03:06 +0000
3919+++ lib/lp/services/worlddata/doc/language.txt 2012-01-24 12:44:15 +0000
3920@@ -249,12 +249,12 @@
3921 >>> translator_30.addLanguage(sr)
3922 >>> translator_40 = factory.makePerson(name=u'serbian-translator-karma-40')
3923 >>> translator_40.addLanguage(sr)
3924- >>> from lp.testing.layers import LaunchpadZopelessLayer
3925- >>> LaunchpadZopelessLayer.commit()
3926
3927 # We need to fake some Karma.
3928 >>> from lp.registry.model.karma import KarmaCategory, KarmaCache
3929- >>> LaunchpadZopelessLayer.switchDbUser('karma')
3930+ >>> from lp.testing.dbuser import switch_dbuser
3931+
3932+ >>> switch_dbuser('karma')
3933 >>> translations_category = KarmaCategory.selectOne(
3934 ... KarmaCategory.name=='translations')
3935 >>> karma = KarmaCache(person=translator_30,
3936@@ -269,8 +269,7 @@
3937 >>> karma = KarmaCache(person=translator_40,
3938 ... category=translations_category,
3939 ... karmavalue=40)
3940- >>> LaunchpadZopelessLayer.commit()
3941- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
3942+ >>> switch_dbuser('launchpad')
3943 >>> for translator in sr.translators:
3944 ... print translator.name
3945 serbian-translator-karma-40
3946
3947=== modified file 'lib/lp/soyuz/doc/buildd-scoring.txt'
3948--- lib/lp/soyuz/doc/buildd-scoring.txt 2011-12-30 06:14:56 +0000
3949+++ lib/lp/soyuz/doc/buildd-scoring.txt 2012-01-24 12:44:15 +0000
3950@@ -28,21 +28,20 @@
3951 >>> hoary386.title
3952 u'The Hoary Hedgehog Release for i386 (x86)'
3953
3954- >>> from lp.services.database.sqlbase import commit
3955 >>> from lp.registry.interfaces.pocket import PackagePublishingPocket
3956 >>> from lp.registry.interfaces.sourcepackage import SourcePackageUrgency
3957 >>> from lp.soyuz.enums import PackagePublishingStatus
3958 >>> from lp.soyuz.tests.test_publishing import (
3959 ... SoyuzTestPublisher)
3960- >>> from lp.testing.layers import LaunchpadZopelessLayer
3961+ >>> from lp.testing.dbuser import (
3962+ ... lp_dbuser,
3963+ ... switch_dbuser,
3964+ ... )
3965
3966 >>> test_publisher = SoyuzTestPublisher()
3967
3968- >>> commit()
3969- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
3970- >>> test_publisher.prepareBreezyAutotest()
3971- >>> commit()
3972- >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
3973+ >>> with lp_dbuser():
3974+ ... test_publisher.prepareBreezyAutotest()
3975
3976 >>> version = 1
3977
3978@@ -51,15 +50,12 @@
3979 ... pocket=PackagePublishingPocket.RELEASE,
3980 ... date_created=LOCAL_NOW, manual=False, archive=None):
3981 ... global version
3982- ... commit()
3983- ... LaunchpadZopelessLayer.switchDbUser('launchpad')
3984- ... pub = test_publisher.getPubSource(
3985- ... sourcename='test-build', version=str(version),
3986- ... distroseries=hoary, component=component_name,
3987- ... urgency=urgency, pocket=pocket,
3988- ... status=PackagePublishingStatus.PUBLISHED, archive=archive)
3989- ... commit()
3990- ... LaunchpadZopelessLayer.switchDbUser(test_dbuser)
3991+ ... with lp_dbuser():
3992+ ... pub = test_publisher.getPubSource(
3993+ ... sourcename='test-build', version=str(version),
3994+ ... distroseries=hoary, component=component_name,
3995+ ... urgency=urgency, pocket=pocket,
3996+ ... status=PackagePublishingStatus.PUBLISHED, archive=archive)
3997 ... version += 1
3998 ... build = pub.sourcepackagerelease.createBuild(
3999 ... hoary386, pub.pocket, pub.archive)
4000@@ -86,8 +82,7 @@
4001
4002 If the archive is private, its score is boosted by 10000:
4003
4004- >>> commit()
4005- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
4006+ >>> switch_dbuser('launchpad')
4007 >>> private_ppa = factory.makeArchive()
4008 >>> private_ppa.buildd_secret = "secret"
4009 >>> private_ppa.private = True
4010@@ -113,7 +108,7 @@
4011 12415
4012
4013 >>> private_ppa.relative_build_score = 0
4014- >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4015+ >>> switch_dbuser(test_dbuser)
4016
4017
4018 * 1500 points for pocket 'RELEASE',
4019@@ -251,7 +246,7 @@
4020 be considered when there is nothing else to build. Even language-packs
4021 and build retries will be built before them.
4022
4023- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
4024+ >>> switch_dbuser('launchpad')
4025 >>> from lp.soyuz.enums import ArchivePurpose
4026 >>> from lp.soyuz.interfaces.archive import IArchiveSet
4027 >>> copy = getUtility(IArchiveSet).new(
4028
4029=== modified file 'lib/lp/soyuz/doc/closing-bugs-from-changelogs.txt'
4030--- lib/lp/soyuz/doc/closing-bugs-from-changelogs.txt 2011-12-30 06:14:56 +0000
4031+++ lib/lp/soyuz/doc/closing-bugs-from-changelogs.txt 2012-01-24 12:44:15 +0000
4032@@ -22,12 +22,13 @@
4033 package, but the bugs they reference may be filed on the generic
4034 distribution package.
4035
4036- >>> from lp.testing.layers import LaunchpadZopelessLayer
4037 >>> from lp.bugs.interfaces.bug import CreateBugParams
4038 >>> from lp.registry.interfaces.distribution import IDistributionSet
4039+ >>> from lp.testing.dbuser import switch_dbuser
4040+
4041 >>> login('no-priv@canonical.com')
4042
4043- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
4044+ >>> switch_dbuser('launchpad')
4045
4046 >>> ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
4047 >>> ubuntu_hoary = ubuntu.getSeries('hoary')
4048@@ -83,16 +84,14 @@
4049 >>> queue_item = add_package_upload(pmount_release, pmount_bug_id)
4050
4051 # Need to commit the transaction so that the changes file can be
4052- # downloaded from the Librarian.
4053- >>> from lp.services.database.sqlbase import commit
4054- >>> commit()
4055+ # downloaded from the Librarian. switch_dbuser takes care of this.
4056+ >>> switch_dbuser(test_dbuser)
4057
4058 Right after the queue items have been processed by the publishing
4059 scripts, close_bugs_for_queue_item() is called with the id of each queue item
4060 that has been published. Passing a queue item with a Launchpad-bugs-fixed
4061 header will close the specified bug.
4062
4063- >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4064 >>> from lp.bugs.interfaces.bug import IBugSet
4065
4066 >>> def print_single_task_status(bug_id):
4067@@ -112,8 +111,7 @@
4068 The changelog associated with the SourcePackageRelease is automatically
4069 added as a comment from the janitor.
4070
4071- >>> commit()
4072- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
4073+ >>> switch_dbuser('launchpad')
4074 >>> pmount_bug = getUtility(IBugSet).get(pmount_bug_id)
4075 >>> last_comment = pmount_bug.messages[-1]
4076 >>> print pmount_release.creator.displayname
4077@@ -194,11 +192,9 @@
4078 ... print "Before:"
4079 ... for bug_id in bug_id_list:
4080 ... print print_single_task_status(bug_id)
4081- ... commit()
4082- ... LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4083+ ... switch_dbuser(test_dbuser)
4084 ... close_bugs_for_queue_item(queue_item)
4085- ... commit()
4086- ... LaunchpadZopelessLayer.switchDbUser('launchpad')
4087+ ... switch_dbuser('launchpad')
4088 ... print "After:"
4089 ... for bug_id in bug_id_list:
4090 ... print print_single_task_status(bug_id)
4091@@ -291,8 +287,7 @@
4092 The closing of bugs are done in process-accepted.py, right after the
4093 queue items have been processed.
4094
4095- >>> commit()
4096- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
4097+ >>> switch_dbuser('launchpad')
4098
4099 >>> queue_item = add_package_upload(pmount_release, fixing_text)
4100 >>> queue_item.setAccepted()
4101@@ -316,8 +311,7 @@
4102 >>> print_single_task_status(another_pmount_bug_id)
4103 'CONFIRMED'
4104
4105- >>> commit()
4106- >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4107+ >>> switch_dbuser(test_dbuser)
4108
4109 >>> import os.path
4110 >>> import subprocess
4111
4112=== modified file 'lib/lp/soyuz/doc/distroarchseriesbinarypackage.txt'
4113--- lib/lp/soyuz/doc/distroarchseriesbinarypackage.txt 2011-12-30 06:14:56 +0000
4114+++ lib/lp/soyuz/doc/distroarchseriesbinarypackage.txt 2012-01-24 12:44:15 +0000
4115@@ -205,8 +205,9 @@
4116 First, update the cache tables for Celso's PPA:
4117
4118 >>> from lp.services.config import config
4119+ >>> from lp.testing.dbuser import switch_dbuser
4120 >>> from lp.testing.layers import LaunchpadZopelessLayer
4121- >>> LaunchpadZopelessLayer.switchDbUser(config.statistician.dbuser)
4122+ >>> switch_dbuser(config.statistician.dbuser)
4123
4124 >>> from lp.services.log.logger import FakeLogger
4125 >>> from lp.soyuz.model.distributionsourcepackagecache import (
4126@@ -234,7 +235,7 @@
4127 Then, supersede all pmount publications in warty for pmount (this sets
4128 us up to demonstrate bug 208233).
4129
4130- >>> LaunchpadZopelessLayer.switchDbUser('archivepublisher')
4131+ >>> switch_dbuser('archivepublisher')
4132 >>> from lp.soyuz.model.binarypackagename import BinaryPackageName
4133 >>> from lp.soyuz.model.distroarchseries import DistroArchSeries
4134 >>> from lp.soyuz.model.distroarchseriesbinarypackage import (
4135@@ -253,7 +254,7 @@
4136 ... s = p.supersede()
4137 >>> commit()
4138 >>> flush_database_updates()
4139- >>> LaunchpadZopelessLayer.switchDbUser(config.statistician.dbuser)
4140+ >>> switch_dbuser(config.statistician.dbuser)
4141
4142 Now, if that bug is actually fixed, this works:
4143
4144
4145=== modified file 'lib/lp/soyuz/doc/package-arch-specific.txt'
4146--- lib/lp/soyuz/doc/package-arch-specific.txt 2011-12-30 06:14:56 +0000
4147+++ lib/lp/soyuz/doc/package-arch-specific.txt 2012-01-24 12:44:15 +0000
4148@@ -16,11 +16,14 @@
4149
4150 >>> from lp.soyuz.tests.test_publishing import (
4151 ... SoyuzTestPublisher)
4152- >>> from lp.testing.layers import LaunchpadZopelessLayer
4153+ >>> from lp.testing.dbuser import (
4154+ ... lp_dbuser,
4155+ ... switch_dbuser,
4156+ ... )
4157
4158 Publication will be added as 'launchpad' DB user.
4159
4160- >>> LaunchpadZopelessLayer.switchDbUser("launchpad")
4161+ >>> switch_dbuser("launchpad")
4162
4163 >>> test_publisher = SoyuzTestPublisher()
4164 >>> ignore = test_publisher.setUpDefaultDistroSeries(hoary)
4165@@ -43,9 +46,7 @@
4166 Good, all done, we can commit the publications and continue the tests
4167 with the buildmaster DB user.
4168
4169- >>> from lp.services.database.sqlbase import commit
4170- >>> commit()
4171- >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4172+ >>> switch_dbuser(test_dbuser)
4173
4174
4175 == Check the architectures to build ==
4176@@ -153,18 +154,13 @@
4177 >>> from lp.soyuz.enums import (
4178 ... PackagePublishingStatus)
4179
4180- >>> LaunchpadZopelessLayer.switchDbUser("launchpad")
4181-
4182- >>> pub_single = test_publisher.getPubSource(
4183- ... sourcename='single', version='1.0',
4184- ... architecturehintlist="any")
4185-
4186- >>> binaries = test_publisher.getPubBinaries(
4187- ... binaryname='single-bin', pub_source=pub_single,
4188- ... status=PackagePublishingStatus.PUBLISHED)
4189-
4190- >>> commit()
4191- >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4192+ >>> with lp_dbuser():
4193+ ... pub_single = test_publisher.getPubSource(
4194+ ... sourcename='single', version='1.0',
4195+ ... architecturehintlist="any")
4196+ ... binaries = test_publisher.getPubBinaries(
4197+ ... binaryname='single-bin', pub_source=pub_single,
4198+ ... status=PackagePublishingStatus.PUBLISHED)
4199
4200 >>> len(set(pub.binarypackagerelease.name
4201 ... for pub in pub_single.getPublishedBinaries()))
4202@@ -210,16 +206,11 @@
4203 Binary PAS lines are ignored for PPAs as well. We create a binary for
4204 the existing test PPA source publication.
4205
4206- >>> LaunchpadZopelessLayer.switchDbUser("launchpad")
4207-
4208- >>> pub_ppa.archive.require_virtualized = False
4209-
4210- >>> binaries = test_publisher.getPubBinaries(
4211- ... binaryname='ppa-bin', pub_source=pub_ppa,
4212- ... status=PackagePublishingStatus.PUBLISHED)
4213-
4214- >>> commit()
4215- >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4216+ >>> with lp_dbuser():
4217+ ... pub_ppa.archive.require_virtualized = False
4218+ ... binaries = test_publisher.getPubBinaries(
4219+ ... binaryname='ppa-bin', pub_source=pub_ppa,
4220+ ... status=PackagePublishingStatus.PUBLISHED)
4221
4222 And it will build in the same architectures with or without a
4223 corresponding PAS binary line.
4224@@ -241,26 +232,21 @@
4225 We will create a 'multiple' source publication build two binaries,
4226 'bin-one' and 'bin-two'.
4227
4228- >>> LaunchpadZopelessLayer.switchDbUser("launchpad")
4229-
4230- >>> pub_multiple = test_publisher.getPubSource(
4231- ... sourcename='multiple', version='1.1',
4232- ... architecturehintlist="any")
4233-
4234- >>> for build in pub_multiple.createMissingBuilds():
4235- ... bin_one = test_publisher.uploadBinaryForBuild(
4236- ... build, 'bin-one')
4237- ... pub_bin_one = test_publisher.publishBinaryInArchive(
4238- ... bin_one, pub_multiple.archive,
4239- ... status=PackagePublishingStatus.PUBLISHED)
4240- ... bin_two = test_publisher.uploadBinaryForBuild(
4241- ... build, 'bin-two')
4242- ... pub_bin_two = test_publisher.publishBinaryInArchive(
4243- ... bin_two, pub_multiple.archive,
4244- ... status=PackagePublishingStatus.PUBLISHED)
4245-
4246- >>> commit()
4247- >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4248+ >>> with lp_dbuser():
4249+ ... pub_multiple = test_publisher.getPubSource(
4250+ ... sourcename='multiple', version='1.1',
4251+ ... architecturehintlist="any")
4252+ ... for build in pub_multiple.createMissingBuilds():
4253+ ... bin_one = test_publisher.uploadBinaryForBuild(
4254+ ... build, 'bin-one')
4255+ ... pub_bin_one = test_publisher.publishBinaryInArchive(
4256+ ... bin_one, pub_multiple.archive,
4257+ ... status=PackagePublishingStatus.PUBLISHED)
4258+ ... bin_two = test_publisher.uploadBinaryForBuild(
4259+ ... build, 'bin-two')
4260+ ... pub_bin_two = test_publisher.publishBinaryInArchive(
4261+ ... bin_two, pub_multiple.archive,
4262+ ... status=PackagePublishingStatus.PUBLISHED)
4263
4264 >>> len(set(pub.binarypackagerelease.name
4265 ... for pub in pub_multiple.getPublishedBinaries()))
4266
4267=== modified file 'lib/lp/soyuz/doc/package-cache.txt'
4268--- lib/lp/soyuz/doc/package-cache.txt 2011-12-30 06:14:56 +0000
4269+++ lib/lp/soyuz/doc/package-cache.txt 2012-01-24 12:44:15 +0000
4270@@ -487,16 +487,16 @@
4271
4272 We will use `SoyuzTestPublisher` for creating convenient publications.
4273
4274- >>> from lp.services.database.sqlbase import commit
4275- >>> from lp.soyuz.enums import (
4276- ... PackagePublishingStatus)
4277- >>> from lp.soyuz.tests.test_publishing import (
4278- ... SoyuzTestPublisher)
4279- >>> from lp.testing.layers import LaunchpadZopelessLayer
4280+ >>> from lp.soyuz.enums import PackagePublishingStatus
4281+ >>> from lp.soyuz.tests.test_publishing import SoyuzTestPublisher
4282+ >>> from lp.testing.dbuser import (
4283+ ... lp_dbuser,
4284+ ... switch_dbuser,
4285+ ... )
4286
4287 >>> test_publisher = SoyuzTestPublisher()
4288
4289- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
4290+ >>> switch_dbuser('launchpad')
4291
4292 >>> unused = test_publisher.setUpDefaultDistroSeries(warty)
4293 >>> test_publisher.addFakeChroots()
4294@@ -529,8 +529,7 @@
4295 ... set(pub.binarypackagerelease.name for pub in published_binaries))
4296 1
4297
4298- >>> commit()
4299- >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4300+ >>> switch_dbuser(test_dbuser)
4301
4302 Exactly 2 new sources and 2 new binaries will be accounted.
4303
4304@@ -543,7 +542,7 @@
4305
4306 Let's create one source with a single binary in DELETED status.
4307
4308- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
4309+ >>> switch_dbuser('launchpad')
4310
4311 >>> deleted_source = test_publisher.getPubSource(
4312 ... sourcename = 'pending-source',
4313@@ -557,7 +556,7 @@
4314 ... set(pub.binarypackagerelease.name for pub in deleted_binaries))
4315 1
4316
4317- >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4318+ >>> switch_dbuser(test_dbuser)
4319
4320 Distroseries package counters will not account DELETED publications.
4321
4322@@ -702,23 +701,9 @@
4323 ... print '%d binaries cached [%d]' % (
4324 ... archive.binaries_cached, binary_caches.count())
4325 >>> def print_search_results(text, user=None):
4326- ... commit()
4327- ... LaunchpadZopelessLayer.switchDbUser('launchpad')
4328- ... for ppa in ubuntu.searchPPAs(text, user=user):
4329- ... print ppa.displayname
4330- ... LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4331- >>> def enable_archive(archive):
4332- ... commit()
4333- ... LaunchpadZopelessLayer.switchDbUser('launchpad')
4334- ... archive.enable()
4335- ... commit()
4336- ... LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4337- >>> def disable_archive(archive):
4338- ... commit()
4339- ... LaunchpadZopelessLayer.switchDbUser('launchpad')
4340- ... archive.disable()
4341- ... commit()
4342- ... LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4343+ ... with lp_dbuser():
4344+ ... for ppa in ubuntu.searchPPAs(text, user=user):
4345+ ... print ppa.displayname
4346
4347 >>> rebuild_caches(cprov.archive)
4348
4349@@ -731,7 +716,8 @@
4350
4351 When Celso's PPA gets disabled, the indexes remain in the DB.
4352
4353- >>> disable_archive(cprov.archive)
4354+ >>> with lp_dbuser():
4355+ ... cprov.archive.disable()
4356
4357 >>> print_caches(cprov.archive)
4358 3 sources cached [3]
4359@@ -766,7 +752,8 @@
4360 will be re-created when the indexes are rebuilt and the ppa becomes
4361 publicly searchable again.
4362
4363- >>> enable_archive(cprov.archive)
4364+ >>> with lp_dbuser():
4365+ ... cprov.archive.enable()
4366
4367 >>> rebuild_caches(cprov.archive)
4368
4369
4370=== modified file 'lib/lp/soyuz/doc/queuebuilder.txt'
4371--- lib/lp/soyuz/doc/queuebuilder.txt 2011-12-30 06:14:56 +0000
4372+++ lib/lp/soyuz/doc/queuebuilder.txt 2012-01-24 12:44:15 +0000
4373@@ -130,13 +130,11 @@
4374 >>> from lp.registry.interfaces.person import IPersonSet
4375 >>> cprov = getUtility(IPersonSet).getByName('cprov')
4376
4377- >>> from lp.services.database.sqlbase import commit
4378 >>> from lp.soyuz.tests.test_publishing import (
4379 ... SoyuzTestPublisher)
4380- >>> from lp.testing.layers import LaunchpadZopelessLayer
4381+ >>> from lp.testing.dbuser import switch_dbuser
4382
4383- >>> commit()
4384- >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
4385+ >>> switch_dbuser('launchpad')
4386
4387 Let's use SoyuzTestPublisher to create a set of publications in the
4388 exact state to expose the features that we want to test.
4389@@ -288,8 +286,7 @@
4390 >>> old_build_ids.append(failed_build.id)
4391 >>> old_build_ids.append(ok_build.id)
4392
4393- >>> commit()
4394- >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
4395+ >>> switch_dbuser(test_dbuser)
4396
4397
4398 == Create and verify the new builds ==
4399
4400=== modified file 'lib/lp/soyuz/doc/soyuz-set-of-uploads.txt'
4401--- lib/lp/soyuz/doc/soyuz-set-of-uploads.txt 2011-12-30 06:14:56 +0000
4402+++ lib/lp/soyuz/doc/soyuz-set-of-uploads.txt 2012-01-24 12:44:15 +0000
4403@@ -129,6 +129,7 @@
4404 >>> from lp.services.log.logger import FakeLogger
4405 >>> from lp.soyuz.scripts.soyuz_process_upload import (
4406 ... ProcessUpload)
4407+ >>> from lp.testing.dbuser import switch_dbuser
4408 >>> from lp.testing.layers import LaunchpadZopelessLayer
4409 >>> def process_uploads(upload_policy, series, loglevel):
4410 ... """Simulate process-upload.py script run.
4411@@ -145,8 +146,7 @@
4412 ... args.extend(["-s", series])
4413 ... # Run script under 'uploader' DB user. The dbuser argument to the
4414 ... # script constructor is ignored, so we must change DB users here.
4415- ... LaunchpadZopelessLayer.txn.commit()
4416- ... LaunchpadZopelessLayer.switchDbUser(config.uploader.dbuser)
4417+ ... switch_dbuser(config.uploader.dbuser)
4418 ... process = ProcessUpload(
4419 ... 'process-upload', dbuser='ignored', test_args=args)
4420 ... process.logger = FakeLogger()
4421@@ -154,7 +154,7 @@
4422 ... process.logger.setLevel(loglevel)
4423 ... process.txn = LaunchpadZopelessLayer.txn
4424 ... process.main()
4425- ... LaunchpadZopelessLayer.switchDbUser('launchpad')
4426+ ... switch_dbuser('launchpad')
4427
4428 And we need a way to process the accepted queue
4429
4430
4431=== modified file 'lib/lp/soyuz/scripts/tests/test_copypackage.py'
4432--- lib/lp/soyuz/scripts/tests/test_copypackage.py 2012-01-19 19:42:08 +0000
4433+++ lib/lp/soyuz/scripts/tests/test_copypackage.py 2012-01-24 12:44:15 +0000
4434@@ -83,6 +83,7 @@
4435 StormStatementRecorder,
4436 TestCaseWithFactory,
4437 )
4438+from lp.testing.dbuser import switch_dbuser
4439 from lp.testing.layers import (
4440 DatabaseLayer,
4441 LaunchpadFunctionalLayer,
4442@@ -1397,8 +1398,7 @@
4443 archive=archive, version='1.0-2', architecturehintlist='any')
4444 dsp = self.factory.makeDistroSeriesParent()
4445 target_archive = dsp.derived_series.main_archive
4446- self.layer.txn.commit()
4447- self.layer.switchDbUser('archivepublisher')
4448+ switch_dbuser('archivepublisher')
4449 # The real test is that the doCopy doesn't fail.
4450 [copied_source] = self.doCopy(
4451 source, target_archive, dsp.derived_series, source.pocket, False)
4452@@ -1417,8 +1417,7 @@
4453 self.factory.makeSection())
4454 getUtility(ISourcePackageFormatSelectionSet).add(
4455 dsp.derived_series, SourcePackageFormat.FORMAT_1_0)
4456- self.layer.txn.commit()
4457- self.layer.switchDbUser('archivepublisher')
4458+ switch_dbuser('archivepublisher')
4459 [copied_source] = do_copy(
4460 [source], target_archive, dsp.derived_series, source.pocket,
4461 check_permissions=False, overrides=[override])
4462@@ -1735,14 +1734,13 @@
4463 def do_delayed_copy(self, source):
4464 """Execute and return the delayed copy."""
4465
4466- self.layer.switchDbUser(self.dbuser)
4467+ switch_dbuser(self.dbuser)
4468
4469 delayed_copy = _do_delayed_copy(
4470 source, self.copy_archive, self.copy_series, self.copy_pocket,
4471 True)
4472
4473- self.layer.txn.commit()
4474- self.layer.switchDbUser('launchpad')
4475+ switch_dbuser('launchpad')
4476 return delayed_copy
4477
4478 def test_do_delayed_copy_simple(self):
4479@@ -2003,7 +2001,7 @@
4480 self.binaries_pending_ids = [pub.id for pub in pending_binaries]
4481
4482 # Run test cases in the production context.
4483- self.layer.switchDbUser(self.dbuser)
4484+ switch_dbuser(self.dbuser)
4485
4486 def getCopier(self, sourcename='mozilla-firefox', sourceversion=None,
4487 from_distribution='ubuntu', from_suite='warty',
4488@@ -3364,14 +3362,11 @@
4489 test2_tar = test_publisher.addMockFile(
4490 orig_tarball, filecontent='aaabbbccc')
4491 test2_source.sourcepackagerelease.addFile(test2_tar)
4492- # Commit to ensure librarian files are written.
4493- self.layer.txn.commit()
4494- # And set test1 source tarball to be expired
4495- self.layer.switchDbUser('librarian')
4496+ # Set test1 source tarball to be expired.
4497+ switch_dbuser('librarian')
4498 naked_test1 = removeSecurityProxy(test1_tar)
4499 naked_test1.content = None
4500- self.layer.txn.commit()
4501- self.layer.switchDbUser(self.dbuser)
4502+ switch_dbuser(self.dbuser)
4503
4504 checker = CopyChecker(dest_ppa, include_binaries=False)
4505 self.assertIs(
4506
4507=== modified file 'lib/lp/soyuz/scripts/tests/test_expire_archive_files.py'
4508--- lib/lp/soyuz/scripts/tests/test_expire_archive_files.py 2012-01-01 02:58:52 +0000
4509+++ lib/lp/soyuz/scripts/tests/test_expire_archive_files.py 2012-01-24 12:44:15 +0000
4510@@ -18,6 +18,7 @@
4511 from lp.soyuz.scripts.expire_archive_files import ArchiveExpirer
4512 from lp.soyuz.tests.test_publishing import SoyuzTestPublisher
4513 from lp.testing import TestCaseWithFactory
4514+from lp.testing.dbuser import switch_dbuser
4515 from lp.testing.layers import LaunchpadZopelessLayer
4516
4517
4518@@ -30,7 +31,7 @@
4519 """Set up some test publications."""
4520 super(ArchiveExpiryTestBase, self).setUp()
4521 # Configure the test publisher.
4522- self.layer.switchDbUser("launchpad")
4523+ switch_dbuser("launchpad")
4524 self.stp = SoyuzTestPublisher()
4525 self.stp.prepareBreezyAutotest()
4526
4527@@ -52,8 +53,7 @@
4528 def runScript(self):
4529 """Run the expiry script and return."""
4530 script = self.getScript()
4531- self.layer.txn.commit()
4532- self.layer.switchDbUser(self.dbuser)
4533+ switch_dbuser(self.dbuser)
4534 script.main()
4535
4536 def _setUpExpirablePublications(self, archive=None):
4537@@ -203,7 +203,7 @@
4538 # will remove the test publications we just created.
4539 self.layer.txn.commit()
4540 script = self.getScript(['--dry-run'])
4541- self.layer.switchDbUser(self.dbuser)
4542+ switch_dbuser(self.dbuser)
4543 script.main()
4544 self.assertSourceNotExpired(source)
4545 self.assertBinaryNotExpired(binary)
4546@@ -238,8 +238,7 @@
4547 archive=self.archive)
4548 script = self.getScript()
4549 script.blacklist = [self.archive.owner.name, ]
4550- self.layer.txn.commit()
4551- self.layer.switchDbUser(self.dbuser)
4552+ switch_dbuser(self.dbuser)
4553 script.main()
4554 self.assertSourceNotExpired(source)
4555 self.assertBinaryNotExpired(binary)
4556
4557=== modified file 'lib/lp/soyuz/scripts/tests/test_publishdistro.py'
4558--- lib/lp/soyuz/scripts/tests/test_publishdistro.py 2012-01-01 02:58:52 +0000
4559+++ lib/lp/soyuz/scripts/tests/test_publishdistro.py 2012-01-24 12:44:15 +0000
4560@@ -37,6 +37,7 @@
4561 from lp.soyuz.scripts.publishdistro import PublishDistro
4562 from lp.soyuz.tests.test_publishing import TestNativePublishingBase
4563 from lp.testing import TestCaseWithFactory
4564+from lp.testing.dbuser import switch_dbuser
4565 from lp.testing.fakemethod import FakeMethod
4566 from lp.testing.faketransaction import FakeTransaction
4567 from lp.testing.layers import ZopelessDatabaseLayer
4568@@ -57,9 +58,9 @@
4569 publish_distro = PublishDistro(test_args=args)
4570 publish_distro.logger = BufferLogger()
4571 publish_distro.txn = self.layer.txn
4572- self.layer.switchDbUser(config.archivepublisher.dbuser)
4573+ switch_dbuser(config.archivepublisher.dbuser)
4574 publish_distro.main()
4575- self.layer.switchDbUser('launchpad')
4576+ switch_dbuser('launchpad')
4577
4578 def runPublishDistroScript(self):
4579 """Run publish-distro.py, returning the result and output."""
4580
4581=== modified file 'lib/lp/soyuz/scripts/tests/test_queue.py'
4582--- lib/lp/soyuz/scripts/tests/test_queue.py 2011-12-30 01:48:17 +0000
4583+++ lib/lp/soyuz/scripts/tests/test_queue.py 2012-01-24 12:44:15 +0000
4584@@ -63,6 +63,11 @@
4585 person_logged_in,
4586 TestCaseWithFactory,
4587 )
4588+from lp.testing.dbuser import (
4589+ dbuser,
4590+ lp_dbuser,
4591+ switch_dbuser,
4592+ )
4593 from lp.testing.fakemethod import FakeMethod
4594 from lp.testing.layers import (
4595 DatabaseFunctionalLayer,
4596@@ -77,7 +82,7 @@
4597 def setUp(self):
4598 # Switch database user and set isolation level to READ COMMIITTED
4599 # to avoid SERIALIZATION exceptions with the Librarian.
4600- LaunchpadZopelessLayer.switchDbUser(self.dbuser)
4601+ switch_dbuser(self.dbuser)
4602
4603 def _test_display(self, text):
4604 """Store output from queue tool for inspection."""
4605@@ -123,14 +128,13 @@
4606 insertFakeChangesFileForAllPackageUploads()
4607 fake_chroot = LibraryFileAlias.get(1)
4608
4609- LaunchpadZopelessLayer.switchDbUser("testadmin")
4610+ switch_dbuser("testadmin")
4611
4612 ubuntu = getUtility(IDistributionSet)['ubuntu']
4613 breezy_autotest = ubuntu.getSeries('breezy-autotest')
4614 breezy_autotest['i386'].addOrUpdateChroot(fake_chroot)
4615
4616- LaunchpadZopelessLayer.txn.commit()
4617- LaunchpadZopelessLayer.switchDbUser('launchpad')
4618+ switch_dbuser('launchpad')
4619
4620 TestQueueBase.setUp(self)
4621
4622@@ -141,16 +145,14 @@
4623 def uploadPackage(self,
4624 changesfile="suite/bar_1.0-1/bar_1.0-1_source.changes"):
4625 """Helper function to upload a package."""
4626- LaunchpadZopelessLayer.switchDbUser("uploader")
4627- sync_policy = getPolicy(
4628- name='sync', distro='ubuntu', distroseries='breezy-autotest')
4629- bar_src = NascentUpload.from_changesfile_path(
4630- datadir(changesfile),
4631- sync_policy, DevNullLogger())
4632- bar_src.process()
4633- bar_src.do_accept()
4634- LaunchpadZopelessLayer.txn.commit()
4635- LaunchpadZopelessLayer.switchDbUser(self.dbuser)
4636+ with dbuser("uploader"):
4637+ sync_policy = getPolicy(
4638+ name='sync', distro='ubuntu', distroseries='breezy-autotest')
4639+ bar_src = NascentUpload.from_changesfile_path(
4640+ datadir(changesfile),
4641+ sync_policy, DevNullLogger())
4642+ bar_src.process()
4643+ bar_src.do_accept()
4644 return bar_src
4645
4646 def testBrokenAction(self):
4647@@ -279,16 +281,11 @@
4648
4649 # Add a chroot to breezy-autotest/i386, so the system can create
4650 # builds for it.
4651- LaunchpadZopelessLayer.txn.commit()
4652- LaunchpadZopelessLayer.switchDbUser("launchpad")
4653-
4654- a_file = getUtility(ILibraryFileAliasSet)[1]
4655- breezy_autotest = getUtility(
4656- IDistributionSet)['ubuntu']['breezy-autotest']
4657- breezy_autotest['i386'].addOrUpdateChroot(a_file)
4658-
4659- LaunchpadZopelessLayer.txn.commit()
4660- LaunchpadZopelessLayer.switchDbUser(self.dbuser)
4661+ with lp_dbuser():
4662+ a_file = getUtility(ILibraryFileAliasSet)[1]
4663+ breezy_autotest = getUtility(
4664+ IDistributionSet)['ubuntu']['breezy-autotest']
4665+ breezy_autotest['i386'].addOrUpdateChroot(a_file)
4666
4667 queue_action = self.execute_command(
4668 'accept bar', no_mail=False)
4669@@ -308,16 +305,11 @@
4670
4671 # Add a chroot to breezy-autotest/i386, so the system can create
4672 # builds for it.
4673- LaunchpadZopelessLayer.txn.commit()
4674- LaunchpadZopelessLayer.switchDbUser("launchpad")
4675-
4676- a_file = getUtility(ILibraryFileAliasSet)[1]
4677- breezy_autotest = getUtility(
4678- IDistributionSet)['ubuntu']['breezy-autotest']
4679- breezy_autotest['i386'].addOrUpdateChroot(a_file)
4680-
4681- LaunchpadZopelessLayer.txn.commit()
4682- LaunchpadZopelessLayer.switchDbUser(self.dbuser)
4683+ with lp_dbuser():
4684+ a_file = getUtility(ILibraryFileAliasSet)[1]
4685+ breezy_autotest = getUtility(
4686+ IDistributionSet)['ubuntu']['breezy-autotest']
4687+ breezy_autotest['i386'].addOrUpdateChroot(a_file)
4688
4689 queue_action = self.execute_command(
4690 'accept bar', no_mail=False)
4691@@ -353,19 +345,14 @@
4692 bar_src.queue_root.realiseUpload()
4693
4694 # Now make a new bugtask for the "bar" package.
4695- LaunchpadZopelessLayer.txn.commit()
4696- LaunchpadZopelessLayer.switchDbUser("launchpad")
4697-
4698- the_bug_id = 6
4699- bugtask_owner = getUtility(IPersonSet).getByName('kinnison')
4700- ubuntu = getUtility(IDistributionSet)['ubuntu']
4701- ubuntu_bar = ubuntu.getSourcePackage('bar')
4702- the_bug = getUtility(IBugSet).get(the_bug_id)
4703- bugtask = getUtility(IBugTaskSet).createTask(
4704- the_bug, bugtask_owner, ubuntu_bar)
4705-
4706- LaunchpadZopelessLayer.txn.commit()
4707- LaunchpadZopelessLayer.switchDbUser(self.dbuser)
4708+ with lp_dbuser():
4709+ the_bug_id = 6
4710+ bugtask_owner = getUtility(IPersonSet).getByName('kinnison')
4711+ ubuntu = getUtility(IDistributionSet)['ubuntu']
4712+ ubuntu_bar = ubuntu.getSourcePackage('bar')
4713+ the_bug = getUtility(IBugSet).get(the_bug_id)
4714+ bugtask = getUtility(IBugTaskSet).createTask(
4715+ the_bug, bugtask_owner, ubuntu_bar)
4716
4717 # The bugtask starts life as NEW.
4718 the_bug = getUtility(IBugSet).get(the_bug_id)
4719@@ -495,16 +482,12 @@
4720
4721 Further details in bug #59443
4722 """
4723- LaunchpadZopelessLayer.switchDbUser("launchpad")
4724-
4725- # Make breezy-autotest CURRENT in order to accept upload
4726- # to BACKPORTS.
4727- breezy_autotest = getUtility(
4728- IDistributionSet)['ubuntu']['breezy-autotest']
4729- breezy_autotest.status = SeriesStatus.CURRENT
4730-
4731- LaunchpadZopelessLayer.txn.commit()
4732- LaunchpadZopelessLayer.switchDbUser(self.dbuser)
4733+ with lp_dbuser():
4734+ # Make breezy-autotest CURRENT in order to accept upload
4735+ # to BACKPORTS.
4736+ breezy_autotest = getUtility(
4737+ IDistributionSet)['ubuntu']['breezy-autotest']
4738+ breezy_autotest.status = SeriesStatus.CURRENT
4739
4740 # Store the targeted queue item for future inspection.
4741 # Ensure it is what we expect.
4742@@ -543,16 +526,12 @@
4743
4744 Further details in bug #57708
4745 """
4746- LaunchpadZopelessLayer.switchDbUser("launchpad")
4747-
4748- # Make breezy-autotest CURRENT in order to accept upload
4749- # to PROPOSED.
4750- breezy_autotest = getUtility(
4751- IDistributionSet)['ubuntu']['breezy-autotest']
4752- breezy_autotest.status = SeriesStatus.CURRENT
4753-
4754- LaunchpadZopelessLayer.txn.commit()
4755- LaunchpadZopelessLayer.switchDbUser(self.dbuser)
4756+ with lp_dbuser():
4757+ # Make breezy-autotest CURRENT in order to accept upload
4758+ # to PROPOSED.
4759+ breezy_autotest = getUtility(
4760+ IDistributionSet)['ubuntu']['breezy-autotest']
4761+ breezy_autotest.status = SeriesStatus.CURRENT
4762
4763 # Store the targeted queue item for future inspection.
4764 # Ensure it is what we expect.
4765@@ -611,17 +590,13 @@
4766 Step 4: the remaining duplicated cnews item in UNAPPROVED queue can
4767 only be rejected.
4768 """
4769- LaunchpadZopelessLayer.switchDbUser("launchpad")
4770-
4771- # Add a chroot to breezy-autotest/i386, so the system can create
4772- # builds for it.
4773- a_file = getUtility(ILibraryFileAliasSet)[1]
4774- breezy_autotest = getUtility(
4775- IDistributionSet)['ubuntu']['breezy-autotest']
4776- breezy_autotest['i386'].addOrUpdateChroot(a_file)
4777-
4778- LaunchpadZopelessLayer.txn.commit()
4779- LaunchpadZopelessLayer.switchDbUser(self.dbuser)
4780+ with lp_dbuser():
4781+ # Add a chroot to breezy-autotest/i386, so the system can create
4782+ # builds for it.
4783+ a_file = getUtility(ILibraryFileAliasSet)[1]
4784+ breezy_autotest = getUtility(
4785+ IDistributionSet)['ubuntu']['breezy-autotest']
4786+ breezy_autotest['i386'].addOrUpdateChroot(a_file)
4787
4788 # Certify we have a 'cnews' upload duplication in UNAPPROVED.
4789 self.assertQueueLength(
4790@@ -794,15 +769,12 @@
4791 When overriding the component, the archive may change to a
4792 non-existent one so ensure if fails.
4793 """
4794- LaunchpadZopelessLayer.switchDbUser("launchpad")
4795-
4796- ubuntu = getUtility(IDistributionSet)['ubuntu']
4797- proxied_archive = getUtility(IArchiveSet).getByDistroPurpose(
4798- ubuntu, ArchivePurpose.PARTNER)
4799- comm_archive = removeSecurityProxy(proxied_archive)
4800- comm_archive.purpose = ArchivePurpose.PPA
4801- LaunchpadZopelessLayer.txn.commit()
4802- LaunchpadZopelessLayer.switchDbUser(self.dbuser)
4803+ with lp_dbuser():
4804+ ubuntu = getUtility(IDistributionSet)['ubuntu']
4805+ proxied_archive = getUtility(IArchiveSet).getByDistroPurpose(
4806+ ubuntu, ArchivePurpose.PARTNER)
4807+ comm_archive = removeSecurityProxy(proxied_archive)
4808+ comm_archive.purpose = ArchivePurpose.PPA
4809
4810 self.assertRaises(CommandRunnerError,
4811 self.execute_command,
4812@@ -865,7 +837,7 @@
4813 """
4814 # Start off by setting up a packageuploadbuild that points to
4815 # a build with two binaries.
4816- LaunchpadZopelessLayer.switchDbUser("launchpad")
4817+ switch_dbuser("launchpad")
4818
4819 breezy_autotest = getUtility(
4820 IDistributionSet)['ubuntu']['breezy-autotest']
4821@@ -878,8 +850,7 @@
4822
4823 # Switching db users starts a new transaction. We must re-fetch
4824 # breezy-autotest.
4825- LaunchpadZopelessLayer.txn.commit()
4826- LaunchpadZopelessLayer.switchDbUser("queued")
4827+ switch_dbuser("queued")
4828 breezy_autotest = getUtility(
4829 IDistributionSet)['ubuntu']['breezy-autotest']
4830
4831@@ -987,8 +958,7 @@
4832 # the database user change requires a costly commit.
4833 upload = self.factory.makeCopyJobPackageUpload()
4834 action = self.makeQueueAction(upload)
4835- self.layer.txn.commit()
4836- self.layer.switchDbUser(config.uploadqueue.dbuser)
4837+ switch_dbuser(config.uploadqueue.dbuser)
4838
4839 action.displayItem(upload)
4840 self.assertNotEqual(0, action.display.call_count)
4841@@ -1002,8 +972,7 @@
4842 distroseries = self.factory.makeDistroSeries(
4843 status=SeriesStatus.CURRENT)
4844 upload = self.factory.makeCopyJobPackageUpload(distroseries)
4845- self.layer.txn.commit()
4846- self.layer.switchDbUser(config.uploadqueue.dbuser)
4847+ switch_dbuser(config.uploadqueue.dbuser)
4848 upload.acceptFromQueue(DevNullLogger(), dry_run=True)
4849 # Flush changes to make sure we're not caching any updates that
4850 # the database won't allow. If this passes, we've got the
4851@@ -1054,8 +1023,7 @@
4852 # it's unnecessary anyway.
4853 self.patch(action, "displayTitle", FakeMethod)
4854 action.terms = ["source", str(upload.id)]
4855- self.layer.txn.commit()
4856- self.layer.switchDbUser(config.uploadqueue.dbuser)
4857+ switch_dbuser(config.uploadqueue.dbuser)
4858 action.initialize()
4859 action.run()
4860
4861
4862=== modified file 'lib/lp/soyuz/tests/test_binarypackagebuildbehavior.py'
4863--- lib/lp/soyuz/tests/test_binarypackagebuildbehavior.py 2012-01-01 02:58:52 +0000
4864+++ lib/lp/soyuz/tests/test_binarypackagebuildbehavior.py 2012-01-24 12:44:15 +0000
4865@@ -39,6 +39,7 @@
4866 )
4867 from lp.soyuz.enums import ArchivePurpose
4868 from lp.testing import TestCaseWithFactory
4869+from lp.testing.dbuser import switch_dbuser
4870 from lp.testing.layers import LaunchpadZopelessLayer
4871
4872
4873@@ -57,7 +58,7 @@
4874
4875 def setUp(self):
4876 super(TestBinaryBuildPackageBehavior, self).setUp()
4877- self.layer.switchDbUser('testadmin')
4878+ switch_dbuser('testadmin')
4879
4880 def assertExpectedInteraction(self, ignored, call_log, builder, build,
4881 chroot, archive, archive_purpose,
4882@@ -280,7 +281,7 @@
4883
4884 def setUp(self):
4885 super(TestBinaryBuildPackageBehaviorBuildCollection, self).setUp()
4886- self.layer.switchDbUser('testadmin')
4887+ switch_dbuser('testadmin')
4888
4889 self.builder = self.factory.makeBuilder()
4890 self.build = self.factory.makeBinaryPackageBuild(
4891
4892=== modified file 'lib/lp/soyuz/tests/test_distroseriesbinarypackage.py'
4893--- lib/lp/soyuz/tests/test_distroseriesbinarypackage.py 2012-01-01 02:58:52 +0000
4894+++ lib/lp/soyuz/tests/test_distroseriesbinarypackage.py 2012-01-24 12:44:15 +0000
4895@@ -12,7 +12,6 @@
4896 Equals,
4897 NotEquals,
4898 )
4899-import transaction
4900
4901 from lp.services.config import config
4902 from lp.services.log.logger import BufferLogger
4903@@ -23,6 +22,7 @@
4904 StormStatementRecorder,
4905 TestCaseWithFactory,
4906 )
4907+from lp.testing.dbuser import dbuser
4908 from lp.testing.layers import LaunchpadZopelessLayer
4909 from lp.testing.matchers import HasQueryCount
4910
4911@@ -59,15 +59,14 @@
4912 archive=distro_archive_2)
4913
4914 logger = BufferLogger()
4915- transaction.commit()
4916- LaunchpadZopelessLayer.switchDbUser(config.statistician.dbuser)
4917- DistroSeriesPackageCache._update(
4918- self.distroseries, self.binary_package_name, distro_archive_1,
4919- logger)
4920+ with dbuser(config.statistician.dbuser):
4921+ DistroSeriesPackageCache._update(
4922+ self.distroseries, self.binary_package_name, distro_archive_1,
4923+ logger)
4924
4925- DistroSeriesPackageCache._update(
4926- self.distroseries, self.binary_package_name, distro_archive_2,
4927- logger)
4928+ DistroSeriesPackageCache._update(
4929+ self.distroseries, self.binary_package_name, distro_archive_2,
4930+ logger)
4931
4932 self.failUnlessEqual(
4933 'Foo is the best', self.distroseries_binary_package.summary)
4934
4935=== modified file 'lib/lp/soyuz/tests/test_distroseriesdifferencejob.py'
4936--- lib/lp/soyuz/tests/test_distroseriesdifferencejob.py 2012-01-17 21:45:24 +0000
4937+++ lib/lp/soyuz/tests/test_distroseriesdifferencejob.py 2012-01-24 12:44:15 +0000
4938@@ -42,6 +42,7 @@
4939 may_require_job,
4940 )
4941 from lp.testing import TestCaseWithFactory
4942+from lp.testing.dbuser import switch_dbuser
4943 from lp.testing.layers import (
4944 LaunchpadZopelessLayer,
4945 ZopelessDatabaseLayer,
4946@@ -679,14 +680,12 @@
4947 source_package_name)
4948
4949 def runJob(self, job):
4950- transaction.commit()
4951- self.layer.switchDbUser('distroseriesdifferencejob')
4952+ switch_dbuser('distroseriesdifferencejob')
4953 dsdjob = DistroSeriesDifferenceJob(job)
4954 dsdjob.start()
4955 dsdjob.run()
4956 dsdjob.complete()
4957- transaction.commit()
4958- self.layer.switchDbUser('launchpad')
4959+ switch_dbuser('launchpad')
4960
4961 def test_parent_gets_newer(self):
4962 # When a new source package is uploaded to the parent distroseries,
4963@@ -940,9 +939,8 @@
4964 packages = dict(
4965 (user, self.factory.makeSourcePackageName())
4966 for user in script_users)
4967- transaction.commit()
4968 for user in script_users:
4969- self.layer.switchDbUser(user)
4970+ switch_dbuser(user)
4971 try:
4972 create_job(derived, packages[user], parent)
4973 except ProgrammingError, e:
4974@@ -958,9 +956,8 @@
4975 # Check that DB users can query derived series.
4976 script_users = ['queued']
4977 dsp = self.factory.makeDistroSeriesParent()
4978- transaction.commit()
4979 for user in script_users:
4980- self.layer.switchDbUser(user)
4981+ switch_dbuser(user)
4982 list(dsp.parent_series.getDerivedSeries())
4983
4984 def test_passesPackagesetFilter(self):
4985@@ -973,9 +970,8 @@
4986 dsdj = create_job(
4987 dsp.derived_series, spph.sourcepackagerelease.sourcepackagename,
4988 dsp.parent_series)
4989- transaction.commit()
4990
4991- self.layer.switchDbUser('distroseriesdifferencejob')
4992+ switch_dbuser('distroseriesdifferencejob')
4993
4994 dsdj.passesPackagesetFilter()
4995
4996
4997=== modified file 'lib/lp/soyuz/tests/test_doc.py'
4998--- lib/lp/soyuz/tests/test_doc.py 2011-12-30 06:14:56 +0000
4999+++ lib/lp/soyuz/tests/test_doc.py 2012-01-24 12:44:15 +0000
5000@@ -12,6 +12,7 @@
The diff has been truncated for viewing.