addCleanup vs tearDown

Per the addCleanup doc string: Cleanup items are called even if setUp fails (unlike tearDown) addCleanup can be used to register multiple functions, so you could use separate functions for each resource you wish to clean up. That would allow your code to be a bit more reusable/modular.

Python: Write unittest for console print

You can easily capture standard output by just temporarily redirecting sys.stdout to a StringIO object, as follows: import StringIO import sys def foo(inStr): print “hi”+inStr def test_foo(): capturedOutput = StringIO.StringIO() # Create StringIO object sys.stdout = capturedOutput # and redirect stdout. foo(‘test’) # Call unchanged function. sys.stdout = sys.__stdout__ # Reset redirect. print ‘Captured’, capturedOutput.getvalue() … Read more

Patch over a function imported inside another function

You should mock out helpers.do_it_helper: class Test_do_it(unittest.TestCase): def test_do_it(self): with patch(‘helpers.do_it_helper’) as helper_mock: helper_mock.return_value = 12 # test things Here’s an example using mock on os.getcwd(): import unittest from mock import patch def get_cwd(): from os import getcwd return getcwd() class MyTestCase(unittest.TestCase): @patch(‘os.getcwd’) def test_mocked(self, mock_function): mock_function.return_value=”test” self.assertEqual(get_cwd(), ‘test’)

How to assert a dict contains another dict without assertDictContainsSubset in python? [duplicate]

Although I’m using pytest, I found the following idea in a comment. It worked really great for me, so I thought it could be useful here. Python 3: assert dict1.items() <= dict2.items() Python 2: assert dict1.viewitems() <= dict2.viewitems() It works with non-hashable items, but you can’t know exactly which item eventually fails.

Persist variable changes between tests in unittest?

As some comments have echoed, structuring your tests in this manner is probably a design flaw in the tests themselves and you should consider restructuring them. However, if you want to do this and rely on the fact that the test runner you are using executes them in an alphabetical (seemingly) order then I suggest … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)