samedi 18 juin 2016

How do I override imports of other files for unit testing

I am currently attempting to write unit tests for my Main.py's main() function

Here is a simplified version of my Main.py:

from Configuration import Configuration # Configuration.py is a file in the same dir

def main():
  try:
    Configuration('settings.ini')
  except:
    sys.exit(1) # Test path1
  sys.exit(0) # Test path2

if __name__ == '__main__':
    main()

In my Unit TestsMainUnitTests.py I want to import ..Main.py and fake the Configuration class in such a way that I can hit Test path1 and Test path2

I found that i can assert sys.exit() with the following:

with self.assertRaises(SystemExit) as cm:
  main()
self.assertEqual(cm.exception.code, 1)

but I am having trouble overriding the from Configuration import Configuration

Thoughts?

So far I have tried the following within Unit TestsMainUnitTests.py:

class FakeFactory(object):
  def __init__(self, *a):
    pass

sys.modules['Configuration'] = __import__('FakeFactory')

class Configuration(FakeFactory):
  pass

Another example for demonstration:

foo.py:

from bar import a,b

x = a()

class a(object):
  def __init__(self):
    self.q = 2

y = a()

print x.q, y.q # prints '1 2' as intended

b() # I want this to print 2 without modifying bar.py

bar.py:

class a(object):
  def __init__(self):
    self.q = 1

def b():
  t = a()
  print t.q

Aucun commentaire:

Enregistrer un commentaire