Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing time sensitive applications in Python

I've written an auction system in Django. I want to write unit tests but the application is time sensitive (e.g. the amount advertisers are charged is a function of how long their ad has been active on a website). What's a good approach for testing this type of application?

Here's one possible solution: a DateFactory class which provides some methods to generate a predictable date in testing and the realtime value in production. Do you have any thoughts on this approach, or have you tried something else in practice?

like image 518
Tim Graham Avatar asked Oct 18 '25 19:10

Tim Graham


1 Answers

In the link you provided, the author somewhat rejects the idea of adding additional parameters to your methods for the sake of unit testing, but in some cases I think you can justify this as just an extension of your business logic. In my opinion, it's a form of inversion of control that can make your model more flexible and possibly even more expressive. For example:

def is_expired(self, check_date=None):
    _check_date = check_date or datetime.utcnow()
    return self.create_date + timedelta(days=15) < _check_date

Essentially this allows my unit test to supply its own date/time for the purpose of validating my logic.

The argument in the referenced blog seems to be that this mucks up the API. However, I have encountered situations in which production use cases called for supplanting current date/time with an alternate value. In other words, the inversion of control approach eventually became a necessary part of my application.

like image 180
Joe Holloway Avatar answered Oct 20 '25 09:10

Joe Holloway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!