views:

55

answers:

1

I've defined some timestamps for events in the database as auto_now_add, as the information should be stored with it's timestamp the same time the event is stored.

The description of the events is something like

class NewEvent(models.Model):
    '''
    Individual event
    '''
    name = models.CharField(max_length=100)
    quantity = models.FloatField(null=True)
    timestamp = models.DateTimeField(auto_now_add=True)

To test the module, I'm generating some information in the database in the test.py file, this way:

    for event in EVENT_TYPES:
        time = datetime.datetime.now() - datetime.timedelta(days=1)
        for i in range(48):
            time = time.replace(hour=i / 2)
            NewEvent(name=event,
                     timestamp=time,
                     quantity=i).save()

I must generate events with its timestamp of yesterday (the module will then summarize them). The problem is that you can't overwrite the timestamp. The timestamp it's the one when the event it's produced, the documentation states that very clearly.

So, how to generate data with appropiate timestamps for the testing? I've had several ideas:

  • Maybe generate the database data in a different way, outside the Model classes. Where and how?
  • Somehow define a different class or change the class to behave differently during test, something like

_

 if testing:
     timestamp = models.DateTimeField(auto_now_add=True)
 else:
     timestamp = models.DateTimeField(auto_now_add=False)

Or maybe there's an even easier way to do this... Any ideas?

+3  A: 

I've managed to create data overriding the default values using a fixture.

I've created a test_data.json file with the data in the following format:

[
{
    "model": "stats_agg.newevent",
    "pk": 1,
    "fields": {
        "name": "event1",
        "quantity":0.0,
        "timestamp": "2010-02-15 00:27:40"
     }
},
{
    "model": "stats_agg.newevent",
    "pk": 2,
    "fields": {
        "name": "event1",
        "quantity":1.0,
        "timestamp": "2010-02-15 00:27:40"
     }
},
...

and then add to the test unit

class SimpleTest(TestCase):
   fixtures = ['test_data.json']
Khelben
+1: Fixtures rule.
S.Lott