[New-bugs-announce] [issue11664] Add patch method to unittest.TestCase

Éric Araujo report at bugs.python.org
Thu Mar 24 21:43:59 CET 2011

New submission from Éric Araujo <merwok at netwok.org>:

A common thing to do in setUp or test* methods is to replace some module attribute with something else, either to mock an object calling an external resource or to test platform-specific behavior (for example, changing os.name before calling some function).  Care has to be taken to restore the initial object with addCleanup, tearDown or in a finally block.

I propose that a new method TestCase.patch (inspired by mock.patch, but more limited in scope) be added, to allow such usages (each example is standalone):

  def setUp(self):
      self.patch(socket, 'socket', MockSocket)

  def test_default_format(self):
      self.patch(os, 'name', 'posix')
      self.assertEqual(get_default_format(), '.tar.gz')
      self.path(os, 'name', 'nt')
      self.assertEqual(get_default_format(), '.zip')

  def setUp(self):
      self.patch(sys, 'path', sys.path.copy())

In each example, patch(object, attribute, value) does this: save object.attribute, set object.attribute to value, register a cleanup function to restore object.attribute.

I assigned to Michael so that he can kill this idea early if he has reason to do so.  If not, please move stage to “patch needed” (no pun).  I am willing to work on a patch for 3.3 and unittest2 (not sure which is first :)

assignee: michael.foord
components: Library (Lib)
keywords: easy
messages: 132026
nosy: eric.araujo, ezio.melotti, michael.foord
priority: normal
severity: normal
status: open
title: Add patch method to unittest.TestCase
type: feature request
versions: Python 3.3

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list