irongit

Enhanced time synchronization for drf views.

79 lines2.7 KBPython
1import datetime as dt
2from rest_framework.test import APIClient
3from django.test import TestCase
4from example_app.models import Post
5from timecheck.settings import conf
6
7
8def fmt_dt(t: dt.datetime):
9 return dt.datetime.strftime(t, conf["dt_fmt"])
10
11
12class TimeCheckTests(TestCase):
13 def setUp(self):
14 self.client = APIClient()
15 self.now = dt.datetime.now(dt.UTC)
16 self.earlier = self.now - dt.timedelta(seconds=4)
17 self.later = self.now + dt.timedelta(seconds=4)
18 Post.objects.create(lastUpdated=self.now, text="Test")
19
20 def test_get_client_is_newer(self):
21 client_time = fmt_dt(self.later)
22 conf["raise_exception"] = True
23 response = self.client.get("/", HTTP_LASTUPDATED=client_time)
24 self.assertEqual(response.status_code, conf["noupdate_code"])
25 conf["raise_exception"] = False
26 response = self.client.get("/", HTTP_LASTUPDATED=client_time)
27 self.assertEqual(response.status_code, 200)
28
29 def test_get_client_is_older(self):
30 client_time = fmt_dt(self.earlier)
31 response = self.client.get("/", HTTP_LASTUPDATED=client_time)
32 conf["raise_exception"] = True
33 self.assertEqual(response.status_code, 200)
34
35 def test_get_client_is_equal(self):
36 client_time = fmt_dt(self.now)
37 response = self.client.get("/", HTTP_LASTUPDATED=client_time)
38 conf["raise_exception"] = True
39 self.assertEqual(response.status_code, conf["noupdate_code"])
40
41 def test_put_client_is_newer(self):
42 client_time = fmt_dt(self.later)
43 conf["raise_exception"] = True
44 response = self.client.put(
45 "/",
46 {
47 "id": 1,
48 "lastUpdated": client_time,
49 },
50 format="json",
51 )
52 self.assertEqual(response.status_code, 200)
53
54 def test_put_client_is_older(self):
55 client_time = fmt_dt(self.earlier)
56 conf["raise_exception"] = True
57 response = self.client.put(
58 "/",
59 {"lastUpdated": client_time},
60 format="json",
61 )
62 self.assertEqual(response.status_code, conf["noupdate_code"])
63 conf["raise_exception"] = False
64 response = self.client.put(
65 "/",
66 {"lastUpdated": client_time},
67 format="json",
68 )
69 self.assertEqual(response.status_code, 200)
70
71 def test_put_client_is_equal(self):
72 client_time = fmt_dt(self.now)
73 conf["raise_exception"] = True
74 response = self.client.put(
75 "/",
76 {"lastUpdated": client_time},
77 format="json",
78 )
79 self.assertEqual(response.status_code, conf["noupdate_code"])