Fix Python – Running a specific test case in Django when your app has a tests directory

The Django documentation (http://docs.djangoproject.com/en/1.3/topics/testing/#running-tests) says that you can run individual test cases by specifying them:
$ ./manage.py test animals.AnimalTestCase

This assumes that you have your tests in a tests.py file in your Django application. If this is true, then this command works like expected.
I have ….

Fix Python – Mocking python function based on input arguments

We have been using Mock for python for a while.
Now, we have a situation in which we want to mock a function
def foo(self, my_param):
#do something here, assign something to my_result
return my_result

Normally, the way to mock this would be (assuming foo being part of an object)
self.foo = MagicMock(return_value=”mocked!”)

Even, if i ca….

Fix Python – TransactionManagementError “You can’t execute queries until the end of the ‘atomic’ block” while using signals, but only during Unit Testing

I am getting TransactionManagementError when trying to save a Django User model instance and in its post_save signal, I’m saving some models that have the user as the foreign key.
The context and error is pretty similar to this question
django TransactionManagementError when using signals
However, in this case, the error occurs only while unit te….

Fix Python – pytest: assert almost equal

How to do assert almost equal with py.test for floats without resorting to something like:
assert x – 0.00001 <= y <= x + 0.00001 More specifically it will be useful to know a neat solution for quickly compare pairs of float, without unpacking them: assert (1.32, 2.4) == i_return_tuple_of_two_floats() ....

Fix Python – Python mock multiple return values

I am using pythons mock.patch and would like to change the return value for each call.
Here is the caveat:
the function being patched has no inputs, so I can not change the return value based on the input.
Here is my code for reference.
def get_boolean_response():
response = io.prompt(‘y/n’).lower()
while response not in (‘y’, ‘n’, ‘yes’, ….

Fix Python – How do you generate dynamic (parameterized) unit tests in Python?

I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:
import unittest

l = [[“foo”, “a”, “a”,], [“bar”, “a”, “b”], [“lee”, “b”, “b”]]

class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print “test”, name
self.assertEqual(a….

Fix Python – PATH issue with pytest ‘ImportError: No module named YadaYadaYada’

I used easy_install to install pytest on a mac and started writing tests for a project with a file structure likes so:
repo/
|–app.py
|–settings.py
|–models.py
|–tests/
|–test_app.py

run py.test while in the repo directory, everything behaves as you would expect
but when I try that same thing on either linux or windows ….