Testing Django: testing template at different time

28 views
Skip to first unread message

Zaki Akhmad

unread,
Mar 11, 2015, 7:43:35 AM3/11/15
to django...@googlegroups.com
Hello,

I'd like to write a test script for my django app.

Example, if within business hour, my django app will render:
"It's working time!"

And if not within business hour, my django app will render:
"Happy holiday!"

So the views, will check when the url is accessed.

How do I write the test script?
Following django docs here[1], I started to write my test code.

from django.test import Client, TestCase

class TestPage(TestCase):
def test_holiday(self):
response = self.client.get('/day/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "It's working time!")

This test code will success if I run within business hour. But If I
run it not within business hour, the test code will fail.

* How to write a better test code?
* How do I use mock/patch?
* How to write test code that will check the within and not within
business hour in one file that both will success whenever I run the
test code?

[1]https://docs.djangoproject.com/en/1.7/topics/testing/tools/#testing-responses

Thanks,

--
Zaki Akhmad

Collin Anderson

unread,
Mar 12, 2015, 2:32:28 PM3/12/15
to django...@googlegroups.com
Hi,

You could try using freezegun to run the test as if it were a certain time of day.

Or, you could say something like:
if 9 <= datetime.datetime.now().hour < 17:
    self.assertContains(response, "It's working time!") 
else:
    self.assertContains(response, "Happy holiday!")

That way it will at least not fail (most of the time :).

Collin

Zaki Akhmad

unread,
Mar 18, 2015, 4:46:48 PM3/18/15
to django...@googlegroups.com
On Fri, Mar 13, 2015 at 5:32 AM, Collin Anderson <cmawe...@gmail.com> wrote:
> Hi,
>
> You could try using freezegun to run the test as if it were a certain time
> of day.
> https://pypi.python.org/pypi/freezegun

Hi Collin,

thanks for the response.
After spent some time, finally I managed to get the testing.

I put my code snippets here
https://gist.github.com/za/2a217c47582737f88259

> Or, you could say something like:
> if 9 <= datetime.datetime.now().hour < 17:
> self.assertContains(response, "It's working time!")
> else:
> self.assertContains(response, "Happy holiday!")
>
> That way it will at least not fail (most of the time :).

Yes, but my mentor said it's not best practice in testing because we
want to test all the condition whenever we execute the test code.
Reply all
Reply to author
Forward
0 new messages