← Back to team overview

launchpad-reviewers team mailing list archive

[Merge] lp:~gary/launchpad/bug548-db-cleanup into lp:launchpad

 

Gary Poster has proposed merging lp:~gary/launchpad/bug548-db-cleanup into lp:launchpad.

Requested reviews:
  Launchpad code reviewers (launchpad-reviewers)

For more details, see:
https://code.launchpad.net/~gary/launchpad/bug548-db-cleanup/+merge/48844

This branch tests, tweaks, and exercises a test helper I added in the course of working on bug548, dbuser (and the convenience lp_dbuser).

The test helper is a push-pop helper for a pattern found throughout our tests.  It's simple, but lets us remove some code and, IMO, looks nicer too, since it essentially puts setup code in with blocks.


-- 
https://code.launchpad.net/~gary/launchpad/bug548-db-cleanup/+merge/48844
Your team Launchpad code reviewers is requested to review the proposed merge of lp:~gary/launchpad/bug548-db-cleanup into lp:launchpad.
=== added file 'database/schema/patch-2208-38-1.sql'
--- database/schema/patch-2208-38-1.sql	1970-01-01 00:00:00 +0000
+++ database/schema/patch-2208-38-1.sql	2011-02-07 21:00:00 +0000
@@ -0,0 +1,8 @@
+SET client_min_messages=ERROR;
+
+INSERT INTO PersonSettings (person)
+    SELECT id FROM Person WHERE teamowner IS NULL;
+
+INSERT INTO LaunchpadDatabaseRevision VALUES (2208, 38, 1);
+
+

=== modified file 'lib/lp/bugs/doc/bug-set-status.txt'
--- lib/lp/bugs/doc/bug-set-status.txt	2010-10-18 22:24:59 +0000
+++ lib/lp/bugs/doc/bug-set-status.txt	2011-02-07 21:00:00 +0000
@@ -4,29 +4,24 @@
 change the bug's status for that specific target. It expects the user
 changing the status, the target, and the new status.
 
-    >>> from canonical.testing.layers import LaunchpadZopelessLayer
+    >>> from lp.testing.dbuser import lp_dbuser
     >>> from lp.registry.interfaces.person import IPersonSet
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> login('no-priv@xxxxxxxxxxxxx')
-    >>> no_priv = getUtility(IPersonSet).getByName('no-priv')
-
     >>> from lp.bugs.interfaces.bug import CreateBugParams
     >>> from lp.bugs.interfaces.bugtask import BugTaskStatus
     >>> from lp.registry.interfaces.product import IProductSet
-    >>> bug_params = CreateBugParams(
-    ...     owner=no_priv, title='Sample bug', comment='This is a sample bug.')
-    >>> firefox = getUtility(IProductSet).getByName('firefox')
-    >>> bug = firefox.createBug(bug_params)
-    >>> bug_id = bug.id
-
-    # Set a milestone to ensure that the current db user has enough
-    # privileges to access it.
-    >>> [firefox_task] = bug.bugtasks
-    >>> firefox_task.milestone = firefox.getMilestone('1.0')
-
-    >>> from canonical.database.sqlbase import commit
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
+    
+    >>> with lp_dbuser():
+    ...     login('no-priv@xxxxxxxxxxxxx')
+    ...     no_priv = getUtility(IPersonSet).getByName('no-priv')
+    ...     bug_params = CreateBugParams(
+    ...         owner=no_priv, title='Sample bug', comment='This is a sample bug.')
+    ...     firefox = getUtility(IProductSet).getByName('firefox')
+    ...     bug = firefox.createBug(bug_params)
+    ...     bug_id = bug.id
+    ...     # Set a milestone to ensure that the current db user has enough
+    ...     # privileges to access it.
+    ...     [firefox_task] = bug.bugtasks
+    ...     firefox_task.milestone = firefox.getMilestone('1.0')
 
     >>> from lp.bugs.interfaces.bug import IBugSet
     >>> bug = getUtility(IBugSet).get(bug_id)
@@ -89,18 +84,14 @@
 is edited.
 
     >>> from lp.bugs.interfaces.bugtask import IBugTaskSet
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> bug = getUtility(IBugSet).get(bug_id)
-    >>> no_priv = getUtility(IPersonSet).getByName('no-priv')
-    >>> firefox = getUtility(IProductSet).getByName('firefox')
-    >>> firefox_trunk = firefox.getSeries('trunk')
-    >>> getUtility(IBugTaskSet).createTask(
-    ...     bug, productseries=firefox_trunk, owner=no_priv)
-    <BugTask at ...>
+    >>> with lp_dbuser():
+    ...     bug = getUtility(IBugSet).get(bug_id)
+    ...     no_priv = getUtility(IPersonSet).getByName('no-priv')
+    ...     firefox = getUtility(IProductSet).getByName('firefox')
+    ...     firefox_trunk = firefox.getSeries('trunk')
+    ...     ignore = getUtility(IBugTaskSet).createTask(
+    ...         bug, productseries=firefox_trunk, owner=no_priv)
 
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
     >>> bug = getUtility(IBugSet).get(bug_id)
     >>> no_priv = getUtility(IPersonSet).getByName('no-priv')
     >>> firefox = getUtility(IProductSet).getByName('firefox')
@@ -138,25 +129,20 @@
 Setting the status of a distribution or package bugtask work the same as
 for product tasks.
 
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
     >>> from lp.registry.interfaces.distribution import IDistributionSet
-    >>> ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
-
-    # Set a milestone to ensure that the current db user has enough
-    # privileges to access it.
-    >>> ubuntu_hoary = ubuntu.getSeries('hoary')
-
-    # Only owners, experts, or admins can create a milestone.
-    >>> login('foo.bar@xxxxxxxxxxxxx')
-    >>> feature_freeze = ubuntu_hoary.newMilestone('feature-freeze')
-    >>> login('no-priv@xxxxxxxxxxxxx')
-    >>> bug = ubuntu.createBug(bug_params)
-    >>> [ubuntu_bugtask] = bug.bugtasks
-    >>> ubuntu_bugtask.milestone = feature_freeze
-    >>> bug_id = bug.id
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
+    >>> with lp_dbuser():
+    ...     ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
+    ...     # Set a milestone to ensure that the current db user has enough
+    ...     # privileges to access it.
+    ...     ubuntu_hoary = ubuntu.getSeries('hoary')
+    ...     # Only owners, experts, or admins can create a milestone.
+    ...     login('foo.bar@xxxxxxxxxxxxx')
+    ...     feature_freeze = ubuntu_hoary.newMilestone('feature-freeze')
+    ...     login('no-priv@xxxxxxxxxxxxx')
+    ...     bug = ubuntu.createBug(bug_params)
+    ...     [ubuntu_bugtask] = bug.bugtasks
+    ...     ubuntu_bugtask.milestone = feature_freeze
+    ...     bug_id = bug.id
 
     >>> bug = getUtility(IBugSet).get(bug_id)
     >>> no_priv = getUtility(IPersonSet).getByName('no-priv')
@@ -217,18 +203,15 @@
 
     # Need to be privileged user to target the bug to a series.
     >>> login('foo.bar@xxxxxxxxxxxxx')
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> bug = getUtility(IBugSet).get(bug_id)
-    >>> ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
-    >>> ubuntu_hoary = ubuntu.getSeries('hoary')
-    >>> nomination = bug.addNomination(
-    ...     getUtility(ILaunchBag).user, ubuntu_hoary)
-    >>> nomination.approve(getUtility(ILaunchBag).user)
+    >>> with lp_dbuser():
+    ...     bug = getUtility(IBugSet).get(bug_id)
+    ...     ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
+    ...     ubuntu_hoary = ubuntu.getSeries('hoary')
+    ...     nomination = bug.addNomination(
+    ...         getUtility(ILaunchBag).user, ubuntu_hoary)
+    ...     nomination.approve(getUtility(ILaunchBag).user)
     >>> login('no-priv@xxxxxxxxxxxxx')
 
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
     >>> bug = getUtility(IBugSet).get(bug_id)
     >>> no_priv = getUtility(IPersonSet).getByName('no-priv')
     >>> ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
@@ -238,18 +221,15 @@
     True
 
     >>> login('foo.bar@xxxxxxxxxxxxx')
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> bug = getUtility(IBugSet).get(bug_id)
-    >>> ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
-    >>> ubuntu_warty = ubuntu.getSeries('warty')
-    >>> nomination = bug.addNomination(
-    ...     getUtility(ILaunchBag).user, ubuntu_warty)
-    >>> nomination.approve(getUtility(ILaunchBag).user)
+    >>> with lp_dbuser():
+    ...     bug = getUtility(IBugSet).get(bug_id)
+    ...     ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
+    ...     ubuntu_warty = ubuntu.getSeries('warty')
+    ...     nomination = bug.addNomination(
+    ...         getUtility(ILaunchBag).user, ubuntu_warty)
+    ...     nomination.approve(getUtility(ILaunchBag).user)
     >>> login('no-priv@xxxxxxxxxxxxx')
 
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(test_dbuser)
     >>> bug = getUtility(IBugSet).get(bug_id)
     >>> no_priv = getUtility(IPersonSet).getByName('no-priv')
     >>> ubuntu = getUtility(IDistributionSet).getByName('ubuntu')

=== modified file 'lib/lp/bugs/doc/externalbugtracker-comment-imports.txt'
--- lib/lp/bugs/doc/externalbugtracker-comment-imports.txt	2010-12-02 16:13:51 +0000
+++ lib/lp/bugs/doc/externalbugtracker-comment-imports.txt	2011-02-07 21:00:00 +0000
@@ -11,7 +11,7 @@
     >>> from lp.bugs.tests.externalbugtracker import (
     ...     new_bugtracker)
     >>> from canonical.launchpad.interfaces.message import IMessageSet
-    >>> from canonical.testing.layers import LaunchpadZopelessLayer
+    >>> from lp.testing.dbuser import lp_dbuser
     >>> from lp.bugs.interfaces.bug import CreateBugParams
     >>> from lp.bugs.interfaces.bugmessage import IBugMessageSet
     >>> from lp.bugs.interfaces.bugtracker import BugTrackerType
@@ -21,19 +21,15 @@
 
     >>> bug_tracker = new_bugtracker(BugTrackerType.BUGZILLA)
 
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> sample_person = getUtility(IPersonSet).getByEmail(
-    ...     'test@xxxxxxxxxxxxx')
-    >>> firefox = getUtility(IProductSet).getByName('firefox')
-    >>> bug = firefox.createBug(
-    ...     CreateBugParams(sample_person, "Yet another test bug",
-    ...         "Yet another test description.",
-    ...         subscribe_owner=False))
-
-    >>> bug_watch = bug.addWatch(bug_tracker, '123456', sample_person)
-
-    >>> transaction.commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
+    >>> with lp_dbuser():
+    ...     sample_person = getUtility(IPersonSet).getByEmail(
+    ...         'test@xxxxxxxxxxxxx')
+    ...     firefox = getUtility(IProductSet).getByName('firefox')
+    ...     bug = firefox.createBug(
+    ...         CreateBugParams(sample_person, "Yet another test bug",
+    ...             "Yet another test description.",
+    ...             subscribe_owner=False))
+    ...     bug_watch = bug.addWatch(bug_tracker, '123456', sample_person)
 
 The ISupportsCommentImport interface defines the methods that external
 bug trackers which support comment imports must provide. This interface
@@ -288,23 +284,18 @@
 don't have a remote_comment_id are comments waiting to be pushed to the
 remote tracker and will not be returned by getImportedBugMessages()
 
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> bug_watch2 = factory.makeBugWatch('42')
-    >>> bug_watch2.bug.newMessage(
-    ...     owner=bug_watch2.bug.owner, subject='None',
-    ...     content='Imported comment', bugwatch=bug_watch2,
-    ...     remote_comment_id='test')
-    <Message at ...>
-    >>> bug_watch2.bug.newMessage(
-    ...     owner=bug_watch2.bug.owner, subject='None',
-    ...     content='Native comment')
-    <Message at ...>
-    >>> bug_watch2.bug.newMessage(
-    ...     owner=bug_watch2.bug.owner, subject='None',
-    ...     content='Pushable comment', bugwatch=bug_watch2)
-    <Message at ...>
-    >>> transaction.commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
+    >>> with lp_dbuser():
+    ...     bug_watch2 = factory.makeBugWatch('42')
+    ...     ignore = bug_watch2.bug.newMessage(
+    ...         owner=bug_watch2.bug.owner, subject='None',
+    ...         content='Imported comment', bugwatch=bug_watch2,
+    ...         remote_comment_id='test')
+    ...     ignore = bug_watch2.bug.newMessage(
+    ...         owner=bug_watch2.bug.owner, subject='None',
+    ...         content='Native comment')
+    ...     ignore = bug_watch2.bug.newMessage(
+    ...         owner=bug_watch2.bug.owner, subject='None',
+    ...         content='Pushable comment', bugwatch=bug_watch2)
 
     >>> for bug_message in bug_watch2.getImportedBugMessages():
     ...     print bug_message.message.text_contents
@@ -323,19 +314,16 @@
 We can demonstrate this by creating two messages with the same message
 ID.
 
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> message_one = getUtility(IMessageSet).fromText(
-    ...     "Example Message", "With example content for you to read.")
-    >>> message_two = getUtility(IMessageSet).fromText(
-    ...     "Example Message", "With example content for you to read.",
-    ...     rfc822msgid=message_one.rfc822msgid)
+    >>> with lp_dbuser():
+    ...     message_one = getUtility(IMessageSet).fromText(
+    ...         "Example Message", "With example content for you to read.")
+    ...     message_two = getUtility(IMessageSet).fromText(
+    ...         "Example Message", "With example content for you to read.",
+    ...         rfc822msgid=message_one.rfc822msgid)
 
     >>> message_one.rfc822msgid == message_two.rfc822msgid
     True
 
-    >>> transaction.commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
-
 We will use message_one to represent a message which was sent directly
 to Launchpad. Since it was a comment on a bug, we link it to that bug.
 
@@ -384,16 +372,14 @@
 We'll create a bug watch and add a listener to check for Karma events.
 
     >>> from lp.testing.karma import KarmaAssignedEventListener
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> bug_watch = factory.makeBugWatch('123456')
-    >>> karma_helper = KarmaAssignedEventListener()
-    >>> karma_helper.register_listener()
+    >>> with lp_dbuser():
+    ...     bug_watch = factory.makeBugWatch('123456')
+    ...     karma_helper = KarmaAssignedEventListener()
+    ...     karma_helper.register_listener()
 
 Importing a comment with a CVE reference will produce a CVE link in
 Launchpad but will result in no Karma records being created.
 
-    >>> transaction.commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
     >>> external_bugtracker.remote_comments = {
     ...     '5':"A comment containing a CVE entry: CVE-1991-9911."}
     >>> bugwatch_updater = make_bug_watch_updater(
@@ -451,14 +437,12 @@
     ...     old_notifications.update(new_notifications)
     ...     return new_notifications
 
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
     >>> import pytz
     >>> from datetime import datetime, timedelta
     >>> now = datetime(2008, 9, 12, 15, 30, 45, tzinfo=pytz.timezone('UTC'))
-    >>> test_bug = factory.makeBug(date_created=now)
-    >>> bug_watch = factory.makeBugWatch('42', bug=test_bug)
-    >>> transaction.commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
+    >>> with lp_dbuser():
+    ...     test_bug = factory.makeBug(date_created=now)
+    ...     bug_watch = factory.makeBugWatch('42', bug=test_bug)
 
     >>> get_new_notifications(bug_watch.bug)
     [...]

=== modified file 'lib/lp/bugs/doc/externalbugtracker-trac-lp-plugin.txt'
--- lib/lp/bugs/doc/externalbugtracker-trac-lp-plugin.txt	2010-10-18 22:24:59 +0000
+++ lib/lp/bugs/doc/externalbugtracker-trac-lp-plugin.txt	2011-02-07 21:00:00 +0000
@@ -33,7 +33,7 @@
     >>> from canonical.config import config
     >>> from canonical.launchpad.interfaces.logintoken import ILoginTokenSet
     >>> from canonical.launchpad.webapp.url import urlappend
-    >>> from canonical.testing.layers import LaunchpadZopelessLayer
+    >>> from lp.testing.dbuser import lp_dbuser
 
     >>> class FakeResponse:
     ...     def __init__(self):
@@ -41,27 +41,25 @@
 
     >>> class TestTracLPPlugin(TracLPPlugin):
     ...     def urlopen(self, url):
-    ...         LaunchpadZopelessLayer.switchDbUser('launchpad')
-    ...         base_auth_url = urlappend(self.baseurl, 'launchpad-auth')
-    ...         if not url.startswith(base_auth_url + '/'):
-    ...             raise AssertionError("Unexpected URL: %s" % url)
-    ...         token_text = url.split('/')[-1]
-    ...         token = getUtility(ILoginTokenSet)[token_text]
-    ...         if token.tokentype.name != 'BUGTRACKER':
-    ...             raise AssertionError(
-    ...                 'Invalid token type: %s' % token.tokentype.name)
-    ...         if token.date_consumed is not None:
-    ...             raise AssertionError("Token has already been consumed.")
-    ...         token.consume()
-    ...         print "Successfully validated the token."
-    ...
-    ...         cookie_string = (
-    ...             'trac_auth=random_token-' + str(random.random()))
-    ...         self._xmlrpc_transport.setCookie(cookie_string)
-    ...
-    ...         response = FakeResponse()
-    ...         response.headers['Set-Cookie'] = cookie_string
-    ...         LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
+    ...         with lp_dbuser():
+    ...             base_auth_url = urlappend(self.baseurl, 'launchpad-auth')
+    ...             if not url.startswith(base_auth_url + '/'):
+    ...                 raise AssertionError("Unexpected URL: %s" % url)
+    ...             token_text = url.split('/')[-1]
+    ...             token = getUtility(ILoginTokenSet)[token_text]
+    ...             if token.tokentype.name != 'BUGTRACKER':
+    ...                 raise AssertionError(
+    ...                     'Invalid token type: %s' % token.tokentype.name)
+    ...             if token.date_consumed is not None:
+    ...                 raise AssertionError(
+    ...                     "Token has already been consumed.")
+    ...             token.consume()
+    ...             print "Successfully validated the token."
+    ...             cookie_string = (
+    ...                 'trac_auth=random_token-' + str(random.random()))
+    ...             self._xmlrpc_transport.setCookie(cookie_string)
+    ...             response = FakeResponse()
+    ...             response.headers['Set-Cookie'] = cookie_string
     ...
     ...         return response
 
@@ -311,7 +309,8 @@
 three methods: getCommentIds(), getPosterForComment() and
 getMessageForComment().
 
-    >>> from lp.bugs.interfaces.externalbugtracker import ISupportsCommentImport
+    >>> from lp.bugs.interfaces.externalbugtracker import (
+    ...     ISupportsCommentImport)
     >>> ISupportsCommentImport.providedBy(trac)
     True
 
@@ -337,7 +336,6 @@
 
 We also need an example Bug, BugTracker and BugWatch.
 
-    >>> from canonical.database.sqlbase import commit
     >>> from lp.bugs.interfaces.bug import CreateBugParams
     >>> from lp.bugs.interfaces.bugtracker import BugTrackerType
     >>> from lp.registry.interfaces.person import IPersonSet
@@ -347,22 +345,18 @@
 
     >>> bug_tracker = new_bugtracker(BugTrackerType.TRAC)
 
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> sample_person = getUtility(IPersonSet).getByEmail(
-    ...     'test@xxxxxxxxxxxxx')
-    >>> firefox = getUtility(IProductSet).getByName('firefox')
-    >>> bug = firefox.createBug(
-    ...     CreateBugParams(sample_person, "Yet another test bug",
-    ...         "Yet another test description.",
-    ...         subscribe_owner=False))
-
-    >>> bug_watch = bug.addWatch(bug_tracker, '1', sample_person)
-    >>> bug_watch_two = bug.addWatch(bug_tracker, '2', sample_person)
-    >>> bug_watch_three = bug.addWatch(bug_tracker, '3', sample_person)
-    >>> bug_watch_broken = bug.addWatch(bug_tracker, '123', sample_person)
-
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
+    >>> with lp_dbuser():
+    ...     sample_person = getUtility(IPersonSet).getByEmail(
+    ...         'test@xxxxxxxxxxxxx')
+    ...     firefox = getUtility(IProductSet).getByName('firefox')
+    ...     bug = firefox.createBug(
+    ...         CreateBugParams(sample_person, "Yet another test bug",
+    ...             "Yet another test description.",
+    ...             subscribe_owner=False))
+    ...     bug_watch = bug.addWatch(bug_tracker, '1', sample_person)
+    ...     bug_watch_two = bug.addWatch(bug_tracker, '2', sample_person)
+    ...     bug_watch_three = bug.addWatch(bug_tracker, '3', sample_person)
+    ...     bug_watch_broken = bug.addWatch(bug_tracker, '123', sample_person)
 
 getCommentIds() returns all the comment IDs for a given remote bug.
 bug_watch is against remote bug 1, which has one comment.
@@ -478,7 +472,8 @@
 ISupportsCommentPushing interface, which allows Launchpad to use it to
 push comments to the remote bug tracker.
 
-    >>> from lp.bugs.interfaces.externalbugtracker import ISupportsCommentPushing
+    >>> from lp.bugs.interfaces.externalbugtracker import (
+    ...     ISupportsCommentPushing)
     >>> ISupportsCommentPushing.providedBy(trac)
     True
 
@@ -490,15 +485,10 @@
 
 To demonstrate this method, we'll create a comment to push.
 
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-
     >>> from canonical.launchpad.interfaces.message import IMessageSet
-    >>> message = getUtility(IMessageSet).fromText(
-    ...     "A subject", "An example comment to push.", poster)
-
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.checkwatches.dbuser)
+    >>> with lp_dbuser():
+    ...     message = getUtility(IMessageSet).fromText(
+    ...         "A subject", "An example comment to push.", poster)
 
 Calling addRemoteComment() on our TracLPPlugin instance will push the
 comment to the remote bug tracker. We'll add it to bug three on the

=== modified file 'lib/lp/bugs/tests/bugs-emailinterface.txt'
--- lib/lp/bugs/tests/bugs-emailinterface.txt	2011-01-20 17:47:37 +0000
+++ lib/lp/bugs/tests/bugs-emailinterface.txt	2011-02-07 21:00:00 +0000
@@ -1236,22 +1236,20 @@
 bugs directly to series.
 
     >>> from canonical.config import config
-    >>> from canonical.testing.layers import LaunchpadZopelessLayer
+    >>> from lp.testing.dbuser import lp_dbuser
     >>> from lp.registry.interfaces.distribution import IDistributionSet
 
     # The script's default user doesn't have permission to change the driver.
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> login('foo.bar@xxxxxxxxxxxxx')
-    >>> ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
-    >>> ubuntu.driver = getUtility(IPersonSet).getByEmail(
-    ...     sampledata.USER_EMAIL)
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
+    >>> with lp_dbuser():
+    ...     login('foo.bar@xxxxxxxxxxxxx')
+    ...     ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
+    ...     ubuntu.driver = getUtility(IPersonSet).getByEmail(
+    ...         sampledata.USER_EMAIL)
+
     >>> login(sampledata.USER_EMAIL)
     >>> sync(bug)
 
-Now a new bugtask for the series will be create directly.
+Now a new bugtask for the series will be created directly.
 
     >>> submit_commands(bug, 'affects ubuntu/grumpy')
 
@@ -1294,13 +1292,11 @@
 As with the example with no source package above; if the user isn't a
 driver of the series, only a nomination will be created.
 
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> login('foo.bar@xxxxxxxxxxxxx')
-    >>> ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
-    >>> ubuntu.driver = None
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
+    >>> with lp_dbuser():
+    ...     login('foo.bar@xxxxxxxxxxxxx')
+    ...     ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
+    ...     ubuntu.driver = None
+
     >>> login(sampledata.USER_EMAIL)
 
     >>> bug = new_firefox_bug()
@@ -1398,12 +1394,10 @@
 
 Bug supervisors can set some restricted statuses:
 
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> login('foo.bar@xxxxxxxxxxxxx')
-    >>> upstream_task.pillar.setBugSupervisor(email_user, email_user)
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
+    >>> with lp_dbuser():
+    ...     login('foo.bar@xxxxxxxxxxxxx')
+    ...     upstream_task.pillar.setBugSupervisor(email_user, email_user)
+
     >>> sync(bug_four)
     >>> login_person(email_user)
 
@@ -1422,12 +1416,10 @@
     >>> from lp.bugs.interfaces.bugtask import BugTaskStatus
     >>> upstream_task.transitionToStatus(BugTaskStatus.NEW, email_user)
 
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> login('foo.bar@xxxxxxxxxxxxx')
-    >>> upstream_task.pillar.setBugSupervisor(None, None)
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
+    >>> with lp_dbuser():
+    ...     login('foo.bar@xxxxxxxxxxxxx')
+    ...     upstream_task.pillar.setBugSupervisor(None, None)
+
     >>> login('no-priv@xxxxxxxxxxxxx')
 
     >>> submit_commands(bug_four, 'affects firefox', 'status wontfix')
@@ -1672,16 +1664,12 @@
     >>> from lp.registry.interfaces.distribution import IDistributionSet
     >>> from lp.registry.interfaces.sourcepackagename import ISourcePackageNameSet
 
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-    >>> ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
-    >>> mozilla_name = getUtility(ISourcePackageNameSet)['mozilla-firefox']
-    >>> helge = getUtility(IPersonSet).getByName('kreutzm')
-    >>> mozilla_package = ubuntu.getSourcePackage(mozilla_name)
-    >>> mozilla_package.addBugSubscription(helge, helge)
-    <...StructuralSubscription ...>
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
+    >>> with lp_dbuser():
+    ...     ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
+    ...     mozilla_name = getUtility(ISourcePackageNameSet)['mozilla-firefox']
+    ...     helge = getUtility(IPersonSet).getByName('kreutzm')
+    ...     mozilla_package = ubuntu.getSourcePackage(mozilla_name)
+    ...     ignore = mozilla_package.addBugSubscription(helge, helge)
 
     >>> login('kreutzm@xxxxxxxxxxxxxxxxxxx')
 
@@ -2931,16 +2919,14 @@
     ...     msg=initial_bug_message, datecreated=creation_date))
     >>> commit()
 
-    >>> LaunchpadZopelessLayer.switchDbUser('launchpad')
-
-    >>> from canonical.launchpad.interfaces.launchpad import (
-    ...     ILaunchpadCelebrities)
-    >>> bug_tracker = new_bugtracker(BugTrackerType.TRAC)
-    >>> bug_watch = bug_with_watch.addWatch(
-    ...     bug_tracker, '12345', getUtility(ILaunchpadCelebrities).janitor)
-
-    >>> commit()
-    >>> LaunchpadZopelessLayer.switchDbUser(config.processmail.dbuser)
+    >>> with lp_dbuser():
+    ...     from canonical.launchpad.interfaces.launchpad import (
+    ...         ILaunchpadCelebrities)
+    ...     bug_tracker = new_bugtracker(BugTrackerType.TRAC)
+    ...     bug_watch = bug_with_watch.addWatch(
+    ...         bug_tracker,
+    ...         '12345',
+    ...         getUtility(ILaunchpadCelebrities).janitor)
 
 Someone comments on the remote bug and that bug is imported into
 Launchpad. We'll simulate this locally rather than using the bug

=== modified file 'lib/lp/testing/dbuser.py'
--- lib/lp/testing/dbuser.py	2011-02-04 03:10:07 +0000
+++ lib/lp/testing/dbuser.py	2011-02-07 21:00:00 +0000
@@ -11,7 +11,6 @@
 
 from contextlib import contextmanager
 
-from canonical.database.sqlbase import commit
 from canonical.testing.layers import LaunchpadZopelessLayer
 
 @contextmanager
@@ -24,12 +23,12 @@
     code in the "with" block.
     """
     restore_name = LaunchpadZopelessLayer.txn._dbuser
-    commit()
+    LaunchpadZopelessLayer.txn.commit()
     # Note that this will raise an assertion error if the
     # LaunchpadZopelessLayer is not already set up.
     LaunchpadZopelessLayer.switchDbUser(temporary_name)
     yield
-    commit()
+    LaunchpadZopelessLayer.txn.commit()
     LaunchpadZopelessLayer.switchDbUser(restore_name)
 
 def lp_dbuser():

=== added file 'lib/lp/testing/tests/test_dbuser.py'
--- lib/lp/testing/tests/test_dbuser.py	1970-01-01 00:00:00 +0000
+++ lib/lp/testing/tests/test_dbuser.py	2011-02-07 21:00:00 +0000
@@ -0,0 +1,40 @@
+# Copyright 2011 Canonical Ltd.  This software is licensed under the
+# GNU Affero General Public License version 3 (see the file LICENSE).
+
+"""Test for dbuser helper."""
+
+__metaclass__ = type
+
+from canonical.config import config
+from canonical.launchpad.interfaces.lpstorm import IStore
+from canonical.testing.layers import LaunchpadZopelessLayer
+from lp.registry.model.person import Person
+from lp.testing import TestCase # or TestCaseWithFactory
+from lp.testing.dbuser import dbuser, lp_dbuser
+
+class TestDbUser(TestCase):
+
+    layer = LaunchpadZopelessLayer
+
+    def get_current_dbuser(self):
+        store = IStore(Person)
+        query = store.execute('SELECT current_user;')
+        result = query.get_one()[0]
+        query.close()
+        return result
+
+    def test_dbuser(self):
+        LaunchpadZopelessLayer.switchDbUser(config.uploader.dbuser)
+        self.assertEqual(config.uploader.dbuser, self.get_current_dbuser())
+        with dbuser(config.archivepublisher.dbuser):
+            self.assertEqual(config.archivepublisher.dbuser,
+                             self.get_current_dbuser())
+        self.assertEqual(config.uploader.dbuser, self.get_current_dbuser())
+
+    def test_lp_dpuser(self):
+        LaunchpadZopelessLayer.switchDbUser(config.uploader.dbuser)
+        self.assertEqual(config.uploader.dbuser, self.get_current_dbuser())
+        with lp_dbuser():
+            self.assertEqual('launchpad', self.get_current_dbuser())
+        self.assertEqual(config.uploader.dbuser, self.get_current_dbuser())
+


Follow ups