I track events that repeat on a specific day of the week (for example, on the first Sunday of the month, on the third Friday of the month). I have a DayOfWeek model that stores the day of the week event. It contains the next_day_of_week method to return a date object set to the next occurrence of the day of the week that this instance of the event is installed (this helps to find out when the next event will occur).
For example, on Sunday, 7/3/2011:
- For an object with DayOfWeek set on Sunday, next_day_of_week will return on 7/3/2011.
- For DayOfWeek, installed on Monday, it will be back on 7/4/2011.
- For DayOfWeek, set on Saturday, it will return on 7/9/2011.
And so on. I write unit tests (my first time, did I mention that I'm pretty new to this?) And trying to wrap my head around how to test this method. I know that I need to mock something, but I'm not quite sure what. This question seems to depend on what I'm asking: Python: trying to mock datetime.date.today (), but not working
So I'm trying to make fun of datetime.date in test.py:
class FakeDate(date): "A fake replacement for date that can be mocked for testing." def __new__(cls, *args, **kwargs): return date.__new__(date, *args, **kwargs)
And I create my test case by fixing in the mock class and installing today until 7/3/2011:
class TestDayOfWeek(TestCase): """Test the day of the week functions.""" @mock.patch('datetime.date', FakeDate) def test_valid_my_next_day_of_week_sameday(self): from datetime import date FakeDate.today = classmethod(lambda cls: date(2011, 7, 3))
For reference, here is the model class:
class DayOfWeek(ModelBase): """ Represents a day of the week (on which an event can take place). Because the dates of these events are often designated by terms like 'first Monday' or 'third Friday', this field is useful in determining on which dates individual readings take place. """
So when I run the django test runner, the test fails because my DayOfWeek instance does not seem to use mock datetime.date and instead sees today the actual day. From my reading, I understand that the layout exists only in the testing method, and not before or after. But does this also mean that it does not exist for any objects / methods that are created or called from the test method? Then what is its use? I do not think that the problem, but rather that I am doing something wrong when correcting. Maybe a problem with namespaces? I read this: http://www.voidspace.org.uk/python/mock/patch.html#id2 I will continue to try to fix it and edit it if I can, but until then any pointers will be appreciated!
EDIT: realized that I used datetime.datetime in my model instead of datetime.date. I fixed this and edited the above code, but the main problem of an elegant class that is not used remains.