Dictionaries with volatile values in Python unit tests? -


I have to write a unit test for a function that gives a dictionary. In this dictionary, one of the values ​​is Datetime.datetime.now () which definitely changes with running each test.

I want to fully represent that key right now I have a dictionary comparison function, but I really want to use assertEqual in this way:

  Def my_func (auto): Return {'monkey_head_count': 3, 'monkey_creation': datetime.datetime now ()} ... Unit test class MonkeyTester (unittest.TestCase): def test_myfunc (auto): self.assertEqual (my_func) (), {'Monkey_head_count': 3}) # I want to ignore the timestamp!  

Is there any best practice or elegant solution to do this? I know assertAlmostEqual () , but it is only useful for IORA floats.

Just remove the timestamp from the dict before comparing:

  Class manicaster (one-time testcases): def test_myfunc (self): without_timestamp = my_func () Dell without_tammest ["pander_cration"] Self.assertEqual (without_temstamp, {'monkey_head_count': 3})  

If you are testing yourself a lot of time, which includes datetime.now () then you can close the datetime class for your unit test. Consider this

  import datetime constant_now = datetime.datetime (2009,8,7,6,5,4) old_datetime_class = datetime.datetime class new_datetime (datetime.datetime): @staticmethod Def now (): Return constant_now datetime.datetime = new_datetime  

Now whenever you call datetime.datetime.now () in your unit tests, then It can always be simple if you want to switch back to continuous_imension timestamp and if you want / original datetime.datetime.now ()

< Pre> datetime.datetime = old_datetime_class

and things back This type of thing can be useful, though, in a simple example you gave, I suggest removing the tagstyle before comparing it.


Comments

Popular posts from this blog

c++ - Linux and clipboard -

What is expire header and how to achive them in ASP.NET and PHP? -

sql server - How can I determine which of my SQL 2005 statistics are unused? -