← Back to team overview

launchpad-dev team mailing list archive

Controlling feature flags in tests with the FeatureFixture

 

Hi everyone,

Revision 11853 landed a test helper that allows you to easily set features flags
in your tests.  What follows is a quick how-to for this tool.

The fixture uses the testtools fixtures API to hook into your code.  When it is
installed on a TestCase object, the fixture will be automatically torn down and
reset between tests, restoring all of the originally set flags.  (There is one
gotcha: all existing flags are wiped out by the fixture for the duration of the
test.  If you want them to carry over, you need to do so yourself.)

You can use the fixture three different ways:

  a) With the TestCase.useFixture() method
  b) As a context manager, using the 'with' statement
  c) By directly calling a fixture instance's setUp() and cleanUp() methods


Here is some sample code demonstrating each:


  from lp.services.features.testing import FeatureFixture
  from lp.services.features import getFeatureFlag


  class FeatureTestCase(TestCase):

    layer = DatabaseFunctionalLayer  # Fixtures need the database for now

    def test_useFixture(self):
      # You can use the fixture with the useFixture() TestCase method:
      self.useFixture(FeatureFixture({'reds': 'on'}))
      self.assertEqual(getFeatureFlag('reds'), 'on')

    def test_with_context_manager(self):
      # Or as a context manager:
      with FeatureFixture({'blues': None}):
        self.assertEqual(getFeatureFlag('blues'), None)

    def test_setUp_and_cleanUp(self):
      # You can call a fixture's setUp() and cleanUp() directly.
      # This is good for use in doctests.
      flags = FeatureFixture({'greens': 'mu'})
      flags.setUp()
      self.addCleanup(flags.cleanUp) # or use a try/finally


For more details on using the fixture and other feature flag utilities, check
the module docs in lib/lp/services/features/__init__.py

For sample code:

  lib/lp/services/features/testing.py
  lib/lp/services/features/tests/test_helpers.py
  $ grep -r FeatureFixture lib/lp/

Patches welcome!

-- 
Māris Fogels -- https://launchpad.net/~mars
Launchpad.net -- cross-project collaboration and hosting

Attachment: signature.asc
Description: OpenPGP digital signature


Follow ups