| 1 |
from datetime import datetime, timedelta |
| 2 |
|
| 3 |
from django.db import connection |
| 4 |
from django.db.models import TextField |
| 5 |
from django.db.models.functions import Cast, Now |
| 6 |
from django.test import TestCase |
| 7 |
from django.utils import timezone |
| 8 |
|
| 9 |
from ..models import Article |
| 10 |
|
| 11 |
lorem_ipsum = """ |
| 12 |
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod |
| 13 |
tempor incididunt ut labore et dolore magna aliqua.""" |
| 14 |
|
| 15 |
|
| 16 |
class NowTests(TestCase): |
| 17 |
def test_basic(self): |
| 18 |
a1 = Article.objects.create( |
| 19 |
title="How to Django", |
| 20 |
text=lorem_ipsum, |
| 21 |
written=timezone.now(), |
| 22 |
) |
| 23 |
a2 = Article.objects.create( |
| 24 |
title="How to Time Travel", |
| 25 |
text=lorem_ipsum, |
| 26 |
written=timezone.now(), |
| 27 |
) |
| 28 |
num_updated = Article.objects.filter(id=a1.id, published=None).update( |
| 29 |
published=Now() |
| 30 |
) |
| 31 |
self.assertEqual(num_updated, 1) |
| 32 |
num_updated = Article.objects.filter(id=a1.id, published=None).update( |
| 33 |
published=Now() |
| 34 |
) |
| 35 |
self.assertEqual(num_updated, 0) |
| 36 |
a1.refresh_from_db() |
| 37 |
self.assertIsInstance(a1.published, datetime) |
| 38 |
a2.published = Now() + timedelta(days=2) |
| 39 |
a2.save() |
| 40 |
a2.refresh_from_db() |
| 41 |
self.assertIsInstance(a2.published, datetime) |
| 42 |
self.assertQuerySetEqual( |
| 43 |
Article.objects.filter(published__lte=Now()), |
| 44 |
["How to Django"], |
| 45 |
lambda a: a.title, |
| 46 |
) |
| 47 |
self.assertQuerySetEqual( |
| 48 |
Article.objects.filter(published__gt=Now()), |
| 49 |
["How to Time Travel"], |
| 50 |
lambda a: a.title, |
| 51 |
) |
| 52 |
|
| 53 |
def test_microseconds(self): |
| 54 |
Article.objects.create( |
| 55 |
title="How to Django", |
| 56 |
text=lorem_ipsum, |
| 57 |
written=timezone.now(), |
| 58 |
) |
| 59 |
now_string = ( |
| 60 |
Article.objects.annotate(now_string=Cast(Now(), TextField())) |
| 61 |
.get() |
| 62 |
.now_string |
| 63 |
) |
| 64 |
precision = connection.features.time_cast_precision |
| 65 |
self.assertRegex(now_string, rf"^.*\.\d{{1,{precision}}}") |