File: tests.py

package info (click to toggle)
django-auditlog 3.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 620 kB
  • sloc: python: 5,005; makefile: 21
file content (2965 lines) | stat: -rw-r--r-- 109,032 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
import datetime
import itertools
import json
import random
import warnings
from datetime import timezone
from unittest import mock
from unittest.mock import patch

import freezegun
from dateutil.tz import gettz
from django.apps import apps
from django.conf import settings
from django.contrib.admin.sites import AdminSite
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.db import models
from django.db.models import JSONField, Value
from django.db.models.functions import Now
from django.db.models.signals import pre_save
from django.test import RequestFactory, TestCase, TransactionTestCase, override_settings
from django.urls import resolve, reverse
from django.utils import dateformat, formats
from django.utils import timezone as django_timezone
from django.utils.encoding import smart_str
from django.utils.translation import gettext_lazy as _
from test_app.fixtures.custom_get_cid import get_cid as custom_get_cid
from test_app.models import (
    AdditionalDataIncludedModel,
    AltPrimaryKeyModel,
    AutoManyRelatedModel,
    CharfieldTextfieldModel,
    ChoicesFieldModel,
    CustomMaskModel,
    DateTimeFieldModel,
    JSONModel,
    ManyRelatedModel,
    ManyRelatedOtherModel,
    ModelForReusableThroughModel,
    ModelPrimaryKeyModel,
    NoDeleteHistoryModel,
    NullableJSONModel,
    PostgresArrayFieldModel,
    ProxyModel,
    RelatedModel,
    ReusableThroughRelatedModel,
    SerializeNaturalKeyRelatedModel,
    SerializeOnlySomeOfThisModel,
    SerializePrimaryKeyRelatedModel,
    SerializeThisModel,
    SimpleExcludeModel,
    SimpleIncludeModel,
    SimpleMappingModel,
    SimpleMaskedModel,
    SimpleModel,
    SimpleNonManagedModel,
    SwappedManagerModel,
    UUIDPrimaryKeyModel,
)

from auditlog.admin import LogEntryAdmin
from auditlog.cid import get_cid
from auditlog.context import disable_auditlog, set_actor
from auditlog.diff import mask_str, model_instance_diff
from auditlog.middleware import AuditlogMiddleware
from auditlog.models import DEFAULT_OBJECT_REPR, LogEntry
from auditlog.registry import AuditlogModelRegistry, AuditLogRegistrationError, auditlog
from auditlog.signals import post_log, pre_log


class SimpleModelTest(TestCase):
    def setUp(self):
        self.obj = self.make_object()
        super().setUp()

    def make_object(self):
        return SimpleModel.objects.create(text="I am not difficult.")

    def test_create(self):
        """Creation is logged correctly."""
        # Get the object to work with
        obj = self.obj

        # Check for log entries
        self.assertEqual(obj.history.count(), 1, msg="There is one log entry")

        history = obj.history.get()
        self.check_create_log_entry(obj, history)

    def check_create_log_entry(self, obj, history):
        self.assertEqual(
            history.action, LogEntry.Action.CREATE, msg="Action is 'CREATE'"
        )
        self.assertEqual(history.object_repr, str(obj), msg="Representation is equal")

    def test_update(self):
        """Updates are logged correctly."""
        # Get the object to work with
        obj = self.obj

        # Change something
        self.update(obj)

        # Check for log entries
        self.assertEqual(
            obj.history.filter(action=LogEntry.Action.UPDATE).count(),
            1,
            msg="There is one log entry for 'UPDATE'",
        )

        history = obj.history.get(action=LogEntry.Action.UPDATE)
        self.check_update_log_entry(obj, history)

    def update(self, obj):
        obj.boolean = True
        obj.save()

    def check_update_log_entry(self, obj, history):
        self.assertDictEqual(
            history.changes,
            {"boolean": ["False", "True"]},
            msg="The change is correctly logged",
        )

    def test_update_specific_field_supplied_via_save_method(self):
        obj = self.obj

        # Change 2 fields, but save one only.
        obj.boolean = True
        obj.text = "Short text"
        obj.save(update_fields=["boolean"])

        # This implicitly asserts there is only one UPDATE change since the `.get` would fail otherwise.
        self.assertDictEqual(
            obj.history.get(action=LogEntry.Action.UPDATE).changes,
            {"boolean": ["False", "True"]},
            msg=(
                "Object modifications that are not saved to DB are not logged "
                "when using the `update_fields`."
            ),
        )

    def test_django_update_fields_edge_cases(self):
        """
        The test ensures that if Django's `update_fields` behavior ever changes for special
        values `(None, [])`, the package should too.
        https://docs.djangoproject.com/en/3.2/ref/models/instances/#specifying-which-fields-to-save
        """
        obj = self.obj

        # Change boolean, but save no changes by passing an empty list.
        obj.boolean = True
        obj.save(update_fields=[])

        self.assertEqual(
            obj.history.filter(action=LogEntry.Action.UPDATE).count(),
            0,
            msg="There is no log entries created",
        )
        obj.refresh_from_db()
        self.assertFalse(obj.boolean)  # Change didn't persist in DB as expected.

        # Passing `None` should save both fields according to Django.
        obj.integer = 1
        obj.boolean = True
        obj.save(update_fields=None)
        self.assertDictEqual(
            obj.history.get(action=LogEntry.Action.UPDATE).changes,
            {"boolean": ["False", "True"], "integer": ["None", "1"]},
            msg="The 2 fields changed are correctly logged",
        )

    def test_delete(self):
        """Deletion is logged correctly."""
        # Get the object to work with
        obj = self.obj
        content_type = ContentType.objects.get_for_model(obj.__class__)
        pk = obj.pk

        # Delete the object
        self.delete(obj)

        # Check for log entries
        qs = LogEntry.objects.filter(content_type=content_type, object_pk=pk)
        self.assertEqual(qs.count(), 1, msg="There is one log entry for 'DELETE'")

        history = qs.get()
        self.check_delete_log_entry(obj, history)

    def delete(self, obj):
        obj.delete()

    def check_delete_log_entry(self, obj, history):
        pass

    def test_recreate(self):
        self.obj.delete()
        self.setUp()
        self.test_create()

    def test_create_log_to_object_from_other_database(self):
        msg = "The log should not try to write to the same database as the object"

        instance = self.obj
        # simulate object obtained from a different database (read only)
        instance._state.db = "replica"

        changes = model_instance_diff(None, instance)

        log_entry = LogEntry.objects.log_create(
            instance,
            action=LogEntry.Action.CREATE,
            changes=json.dumps(changes),
        )
        self.assertEqual(
            log_entry._state.db, "default", msg=msg
        )  # must be created in default database

    def test_default_timestamp(self):
        start = django_timezone.now()
        self.test_recreate()
        end = django_timezone.now()
        history = self.obj.history.latest()
        self.assertTrue(start <= history.timestamp <= end)

    def test_manual_timestamp(self):
        timestamp = datetime.datetime(1999, 12, 31, 23, 59, 59, tzinfo=timezone.utc)
        LogEntry.objects.log_create(
            instance=self.obj,
            timestamp=timestamp,
            changes="foo bar",
            action=LogEntry.Action.UPDATE,
        )
        history = self.obj.history.filter(timestamp=timestamp, changes="foo bar")
        self.assertTrue(history.exists())

    def test_create_duplicate_with_pk_none(self):
        initial_entries_count = LogEntry.objects.count()
        obj = self.obj
        obj.pk = None
        obj.save()
        self.assertEqual(LogEntry.objects.count(), initial_entries_count + 1)


class NoActorMixin:
    def check_create_log_entry(self, obj, log_entry):
        super().check_create_log_entry(obj, log_entry)
        self.assertIsNone(log_entry.actor)

    def check_update_log_entry(self, obj, log_entry):
        super().check_update_log_entry(obj, log_entry)
        self.assertIsNone(log_entry.actor)

    def check_delete_log_entry(self, obj, log_entry):
        super().check_delete_log_entry(obj, log_entry)
        self.assertIsNone(log_entry.actor)


class WithActorMixin:
    sequence = itertools.count()

    def setUp(self):
        username = f"actor_{next(self.sequence)}"
        self.user = get_user_model().objects.create(
            username=username,
            email=f"{username}@example.com",
            password="secret",
        )
        super().setUp()

    def tearDown(self):
        user_email = self.user.email
        self.user.delete()
        auditlog_entries = LogEntry.objects.filter(actor_email=user_email).all()
        self.assertIsNotNone(auditlog_entries, msg="All auditlog entries are deleted.")
        super().tearDown()

    def make_object(self):
        with set_actor(self.user):
            return super().make_object()

    def check_create_log_entry(self, obj, log_entry):
        super().check_create_log_entry(obj, log_entry)
        self.assertEqual(log_entry.actor, self.user)
        self.assertEqual(log_entry.actor_email, self.user.email)

    def update(self, obj):
        with set_actor(self.user):
            return super().update(obj)

    def check_update_log_entry(self, obj, log_entry):
        super().check_update_log_entry(obj, log_entry)
        self.assertEqual(log_entry.actor, self.user)
        self.assertEqual(log_entry.actor_email, self.user.email)

    def delete(self, obj):
        with set_actor(self.user):
            return super().delete(obj)

    def check_delete_log_entry(self, obj, log_entry):
        super().check_delete_log_entry(obj, log_entry)
        self.assertEqual(log_entry.actor, self.user)
        self.assertEqual(log_entry.actor_email, self.user.email)


class AltPrimaryKeyModelBase(SimpleModelTest):
    def make_object(self):
        return AltPrimaryKeyModel.objects.create(
            key=str(datetime.datetime.now()), text="I am strange."
        )


class AltPrimaryKeyModelTest(NoActorMixin, AltPrimaryKeyModelBase):
    pass


class AltPrimaryKeyModelWithActorTest(WithActorMixin, AltPrimaryKeyModelBase):
    pass


class UUIDPrimaryKeyModelModelBase(SimpleModelTest):
    def make_object(self):
        return UUIDPrimaryKeyModel.objects.create(text="I am strange.")

    def test_get_for_object(self):
        self.obj.boolean = True
        self.obj.save()

        self.assertEqual(LogEntry.objects.get_for_object(self.obj).count(), 2)

    def test_get_for_objects(self):
        self.obj.boolean = True
        self.obj.save()

        self.assertEqual(
            LogEntry.objects.get_for_objects(UUIDPrimaryKeyModel.objects.all()).count(),
            2,
        )


class UUIDPrimaryKeyModelModelTest(NoActorMixin, UUIDPrimaryKeyModelModelBase):
    pass


class UUIDPrimaryKeyModelModelWithActorTest(
    WithActorMixin, UUIDPrimaryKeyModelModelBase
):
    pass


class ModelPrimaryKeyModelBase(SimpleModelTest):
    def make_object(self):
        self.key = super().make_object()
        return ModelPrimaryKeyModel.objects.create(key=self.key, text="I am strange.")

    def test_create_duplicate_with_pk_none(self):
        pass


class ModelPrimaryKeyModelTest(NoActorMixin, ModelPrimaryKeyModelBase):
    pass


class ModelPrimaryKeyModelWithActorTest(WithActorMixin, ModelPrimaryKeyModelBase):
    pass


# Must inherit from TransactionTestCase to use self.assertNumQueries.
class ModelPrimaryKeyTest(TransactionTestCase):
    def test_get_pk_value(self):
        """
        Test that the primary key can be retrieved without additional database queries.
        """
        key = SimpleModel.objects.create(text="I am not difficult.")
        obj = ModelPrimaryKeyModel.objects.create(key=key, text="I am strange.")
        # Refresh the object so the primary key object is not cached.
        obj.refresh_from_db()
        with self.assertNumQueries(0):
            pk = LogEntry.objects._get_pk_value(obj)
        self.assertEqual(pk, obj.pk)
        self.assertEqual(pk, key.pk)
        # Sanity check: verify accessing obj.key causes database access.
        with self.assertNumQueries(1):
            pk = obj.key.pk
        self.assertEqual(pk, obj.pk)
        self.assertEqual(pk, key.pk)


class ProxyModelBase(SimpleModelTest):
    def make_object(self):
        return ProxyModel.objects.create(text="I am not what you think.")


class ProxyModelTest(NoActorMixin, ProxyModelBase):
    pass


class ProxyModelWithActorTest(WithActorMixin, ProxyModelBase):
    pass


class ManyRelatedModelTest(TestCase):
    """
    Test the behaviour of many-to-many relationships.
    """

    def setUp(self):
        self.obj = ManyRelatedModel.objects.create()
        self.recursive = ManyRelatedModel.objects.create()
        self.related = ManyRelatedOtherModel.objects.create()
        self.obj_reusable = ModelForReusableThroughModel.objects.create()
        self.obj_reusable_related = ReusableThroughRelatedModel.objects.create()
        self.base_log_entry_count = (
            LogEntry.objects.count()
        )  # created by the create() calls above

    def test_recursive(self):
        self.obj.recursive.add(self.recursive)
        self.assertEqual(
            LogEntry.objects.get_for_objects(self.obj.recursive.all()).first(),
            self.recursive.history.first(),
        )

    def test_related_add_from_first_side(self):
        self.obj.related.add(self.related)
        self.assertEqual(
            LogEntry.objects.get_for_objects(self.obj.related.all()).first(),
            self.related.history.first(),
        )
        self.assertEqual(LogEntry.objects.count(), self.base_log_entry_count + 1)

    def test_related_add_from_other_side(self):
        self.related.related.add(self.obj)
        self.assertEqual(
            LogEntry.objects.get_for_objects(self.obj.related.all()).first(),
            self.related.history.first(),
        )
        self.assertEqual(LogEntry.objects.count(), self.base_log_entry_count + 1)

    def test_related_remove_from_first_side(self):
        self.obj.related.add(self.related)
        self.obj.related.remove(self.related)
        self.assertEqual(LogEntry.objects.count(), self.base_log_entry_count + 2)

    def test_related_remove_from_other_side(self):
        self.related.related.add(self.obj)
        self.related.related.remove(self.obj)
        self.assertEqual(LogEntry.objects.count(), self.base_log_entry_count + 2)

    def test_related_clear_from_first_side(self):
        self.obj.related.add(self.related)
        self.obj.related.clear()
        self.assertEqual(LogEntry.objects.count(), self.base_log_entry_count + 2)

    def test_related_clear_from_other_side(self):
        self.related.related.add(self.obj)
        self.related.related.clear()
        self.assertEqual(LogEntry.objects.count(), self.base_log_entry_count + 2)

    def test_additional_data(self):
        self.obj.related.add(self.related)
        log_entry = self.obj.history.first()
        self.assertEqual(
            log_entry.additional_data, {"related_model_id": self.related.id}
        )

    def test_changes(self):
        self.obj.related.add(self.related)
        log_entry = self.obj.history.first()
        self.assertEqual(
            log_entry.changes,
            {
                "related": {
                    "type": "m2m",
                    "operation": "add",
                    "objects": [smart_str(self.related)],
                }
            },
        )

    def test_adding_existing_related_obj(self):
        self.obj.related.add(self.related)
        log_entry = self.obj.history.first()
        self.assertEqual(
            log_entry.changes,
            {
                "related": {
                    "type": "m2m",
                    "operation": "add",
                    "objects": [smart_str(self.related)],
                }
            },
        )
        # Add same related obj again.
        self.obj.related.add(self.related)
        latest_log_entry = self.obj.history.first()
        self.assertEqual(log_entry.id, latest_log_entry.id)

    def test_object_repr_related_deleted(self):
        """No error is raised when __str__() raises ObjectDoesNotExist."""
        # monkey-patching to avoid extra logic in the model
        with mock.patch.object(self.obj.__class__, "__str__") as mock_str:
            mock_str.side_effect = self.related.DoesNotExist("I am fake")
            self.obj.related.add(self.related)
            log_entry = self.obj.history.first()
            self.assertEqual(log_entry.object_repr, DEFAULT_OBJECT_REPR)

    def test_changes_not_duplicated_with_reusable_through_model(self):
        self.obj_reusable.related.add(self.obj_reusable_related)
        entries = self.obj_reusable.history.all()
        self.assertEqual(len(entries), 1)


class MiddlewareTest(TestCase):
    """
    Test the middleware responsible for connecting and disconnecting the signals used in automatic logging.
    """

    def setUp(self):
        self.get_response_mock = mock.Mock()
        self.response_mock = mock.Mock()
        self.middleware = AuditlogMiddleware(get_response=self.get_response_mock)
        self.factory = RequestFactory()
        self.user = User.objects.create_user(
            username="test", email="test@example.com", password="top_secret"
        )

    def side_effect(self, assertion):
        def inner(request):
            assertion()
            return self.response_mock

        return inner

    def assert_has_listeners(self):
        self.assertTrue(pre_save.has_listeners(LogEntry))

    def assert_no_listeners(self):
        self.assertFalse(pre_save.has_listeners(LogEntry))

    def test_request_anonymous(self):
        """No actor will be logged when a user is not logged in."""
        request = self.factory.get("/")
        request.user = AnonymousUser()

        self.get_response_mock.side_effect = self.side_effect(self.assert_has_listeners)

        response = self.middleware(request)

        self.assertIs(response, self.response_mock)
        self.get_response_mock.assert_called_once_with(request)
        self.assert_no_listeners()

    def test_request(self):
        """The actor will be logged when a user is logged in."""
        request = self.factory.get("/")
        request.user = self.user

        self.get_response_mock.side_effect = self.side_effect(self.assert_has_listeners)

        response = self.middleware(request)

        self.assertIs(response, self.response_mock)
        self.get_response_mock.assert_called_once_with(request)
        self.assert_no_listeners()

    def test_exception(self):
        """The signal will be disconnected when an exception is raised."""
        request = self.factory.get("/")
        request.user = self.user

        SomeException = type("SomeException", (Exception,), {})

        self.get_response_mock.side_effect = SomeException

        with self.assertRaises(SomeException):
            self.middleware(request)

        self.assert_no_listeners()

    def test_init_middleware(self):
        with override_settings(AUDITLOG_DISABLE_REMOTE_ADDR="str"):
            with self.assertRaisesMessage(
                TypeError, "Setting 'AUDITLOG_DISABLE_REMOTE_ADDR' must be a boolean"
            ):
                AuditlogMiddleware()

    def test_disable_remote_addr(self):
        with override_settings(AUDITLOG_DISABLE_REMOTE_ADDR=True):
            headers = {"HTTP_X_FORWARDED_FOR": "127.0.0.2"}
            request = self.factory.get("/", **headers)
            remote_addr = self.middleware._get_remote_addr(request)
            self.assertIsNone(remote_addr)

    def test_get_remote_addr(self):
        tests = [  # (headers, expected_remote_addr)
            ({}, "127.0.0.1"),
            ({"HTTP_X_FORWARDED_FOR": "127.0.0.2"}, "127.0.0.2"),
            ({"HTTP_X_FORWARDED_FOR": "127.0.0.3:1234"}, "127.0.0.3"),
            ({"HTTP_X_FORWARDED_FOR": "2606:4700:4700::1111"}, "2606:4700:4700::1111"),
            (
                {"HTTP_X_FORWARDED_FOR": "[2606:4700:4700::1001]:1234"},
                "2606:4700:4700::1001",
            ),
        ]
        for headers, expected_remote_addr in tests:
            with self.subTest(headers=headers):
                request = self.factory.get("/", **headers)
                self.assertEqual(
                    self.middleware._get_remote_addr(request), expected_remote_addr
                )

    def test_get_remote_port(self):
        headers = {
            "HTTP_X_FORWARDED_PORT": "12345",
        }
        request = self.factory.get("/", **headers)
        self.assertEqual(self.middleware._get_remote_port(request), 12345)

    def test_cid(self):
        header = str(settings.AUDITLOG_CID_HEADER).lstrip("HTTP_").replace("_", "-")
        header_meta = "HTTP_" + header.upper().replace("-", "_")
        cid = "random_CID"

        _settings = [
            # these tuples test reading the cid from the header defined in the settings
            ({"AUDITLOG_CID_HEADER": header}, cid),  # x-correlation-id
            ({"AUDITLOG_CID_HEADER": header_meta}, cid),  # HTTP_X_CORRELATION_ID
            ({"AUDITLOG_CID_HEADER": None}, None),
            # these two tuples test using a custom getter.
            # Here, we don't necessarily care about the cid that was set in set_cid
            (
                {"AUDITLOG_CID_GETTER": "test_app.fixtures.custom_get_cid.get_cid"},
                custom_get_cid(),
            ),
            ({"AUDITLOG_CID_GETTER": custom_get_cid}, custom_get_cid()),
        ]
        for setting, expected_result in _settings:
            with self.subTest():
                with self.settings(**setting):
                    request = self.factory.get("/", **{header_meta: cid})
                    self.middleware(request)

                    obj = SimpleModel.objects.create(text="I am not difficult.")
                    history = obj.history.get(action=LogEntry.Action.CREATE)

                    self.assertEqual(history.cid, expected_result)
                    self.assertEqual(get_cid(), expected_result)

    def test_set_actor_anonymous_request(self):
        """
        The remote address will be set even when there is no actor
        """
        remote_addr = "123.213.145.99"
        remote_port = 12345
        actor = None

        with set_actor(actor=actor, remote_addr=remote_addr, remote_port=remote_port):
            obj = SimpleModel.objects.create(text="I am not difficult.")

            history = obj.history.get()
            self.assertEqual(
                history.remote_addr,
                remote_addr,
                msg=f"Remote address is {remote_addr}",
            )
            self.assertEqual(
                history.remote_port,
                remote_port,
                msg=f"Remote port is {remote_port}",
            )
            self.assertIsNone(history.actor, msg="Actor is `None` for anonymous user")

    def test_get_actor(self):
        params = [
            (AnonymousUser(), None, "The user is anonymous so the actor is `None`"),
            (self.user, self.user, "The use is authenticated so it is the actor"),
            (None, None, "There is no actor"),
            ("1234", None, "The value of request.user is not a valid user model"),
        ]
        for user, actor, msg in params:
            with self.subTest(msg):
                request = self.factory.get("/")
                request.user = user

                self.assertEqual(self.middleware._get_actor(request), actor)


class SimpleIncludeModelTest(TestCase):
    """Log only changes in include_fields"""

    def test_specified_save_fields_are_ignored_if_not_included(self):
        obj = SimpleIncludeModel.objects.create(label="Initial label", text="Text")
        obj.text = "New text"
        obj.save(update_fields=["text"])

        self.assertEqual(
            obj.history.filter(action=LogEntry.Action.UPDATE).count(),
            0,
            msg="Text change was not logged, even when passed explicitly",
        )

        obj.label = "New label"
        obj.text = "Newer text"
        obj.save(update_fields=["text", "label"])

        self.assertDictEqual(
            obj.history.get(action=LogEntry.Action.UPDATE).changes,
            {"label": ["Initial label", "New label"]},
            msg="Only the label was logged, regardless of multiple entries in `update_fields`",
        )

    def test_register_include_fields(self):
        sim = SimpleIncludeModel(label="Include model", text="Looong text")
        sim.save()
        self.assertEqual(sim.history.count(), 1, msg="There is one log entry")

        # Change label, record
        sim.label = "Changed label"
        sim.save()
        self.assertEqual(sim.history.count(), 2, msg="There are two log entries")

        # Change text, ignore
        sim.text = "Short text"
        sim.save()
        self.assertEqual(sim.history.count(), 2, msg="There are two log entries")


class SimpleExcludeModelTest(TestCase):
    """Log only changes that are not in exclude_fields"""

    def test_specified_save_fields_are_excluded_normally(self):
        obj = SimpleExcludeModel.objects.create(label="Exclude model", text="Text")
        obj.text = "New text"
        obj.save(update_fields=["text"])

        self.assertEqual(
            obj.history.filter(action=LogEntry.Action.UPDATE).count(),
            0,
            msg="Text change was not logged, even when passed explicitly",
        )

    def test_register_exclude_fields(self):
        sem = SimpleExcludeModel(label="Exclude model", text="Looong text")
        sem.save()
        self.assertEqual(sem.history.count(), 1, msg="There is one log entry")

        # Change label, record it.
        sem.label = "Changed label"
        sem.save()
        self.assertEqual(sem.history.count(), 2, msg="There are two log entries")

        # Change text, ignore it.
        sem.text = "Short text"
        sem.save()
        self.assertEqual(sem.history.count(), 2, msg="There are two log entries")


class SimpleMappingModelTest(TestCase):
    """Diff displays fields as mapped field names where available through mapping_fields"""

    def test_register_mapping_fields(self):
        smm = SimpleMappingModel(
            sku="ASD301301A6", vtxt="2.1.5", not_mapped="Not mapped"
        )
        smm.save()
        self.assertEqual(
            smm.history.latest().changes_dict["sku"][1],
            "ASD301301A6",
            msg="The diff function retains 'sku' and can be retrieved.",
        )
        self.assertEqual(
            smm.history.latest().changes_dict["not_mapped"][1],
            "Not mapped",
            msg="The diff function does not map 'not_mapped' and can be retrieved.",
        )
        self.assertEqual(
            smm.history.latest().changes_display_dict["Product No."][1],
            "ASD301301A6",
            msg="The diff function maps 'sku' as 'Product No.' and can be retrieved.",
        )
        self.assertEqual(
            smm.history.latest().changes_display_dict["Version"][1],
            "2.1.5",
            msg=(
                "The diff function maps 'vtxt' as 'Version' through verbose_name"
                " setting on the model field and can be retrieved."
            ),
        )
        self.assertEqual(
            smm.history.latest().changes_display_dict["not mapped"][1],
            "Not mapped",
            msg=(
                "The diff function uses the django default verbose name for 'not_mapped'"
                " and can be retrieved."
            ),
        )


class SimpleMaskedFieldsModelTest(TestCase):
    """Log masked changes for fields in mask_fields"""

    def test_register_mask_fields(self):
        smm = SimpleMaskedModel(address="Sensitive data", text="Looong text")
        smm.save()
        self.assertEqual(
            smm.history.latest().changes_dict["address"][1],
            "*******ve data",
            msg="The diff function masks 'address' field.",
        )

    @override_settings(
        AUDITLOG_MASK_CALLABLE="auditlog_tests.test_app.mask.custom_mask_str"
    )
    def test_global_mask_callable(self):
        """Test that global mask_callable from settings is used when model-specific one is not provided"""
        instance = SimpleMaskedModel.objects.create(
            address="1234567890123456", text="Some text"
        )

        self.assertEqual(
            instance.history.latest().changes_dict["address"][1],
            "****3456",
            msg="The global masking function should be used when model-specific one is not provided",
        )


class AdditionalDataModelTest(TestCase):
    """Log additional data if get_additional_data is defined in the model"""

    def test_model_without_additional_data(self):
        obj_wo_additional_data = SimpleModel.objects.create(
            text="No additional " "data"
        )
        obj_log_entry = obj_wo_additional_data.history.get()
        self.assertIsNone(obj_log_entry.additional_data)

    def test_model_with_additional_data(self):
        related_model = SimpleModel.objects.create(text="Log my reference")
        obj_with_additional_data = AdditionalDataIncludedModel(
            label="Additional data to log entries", related=related_model
        )
        obj_with_additional_data.save()
        self.assertEqual(
            obj_with_additional_data.history.count(), 1, msg="There is 1 log entry"
        )
        log_entry = obj_with_additional_data.history.get()
        extra_data = log_entry.additional_data
        self.assertIsNotNone(extra_data)
        self.assertEqual(
            extra_data["related_model_text"],
            related_model.text,
            msg="Related model's text is logged",
        )
        self.assertEqual(
            extra_data["related_model_id"],
            related_model.id,
            msg="Related model's id is logged",
        )


class DateTimeFieldModelTest(TestCase):
    """Tests if DateTimeField changes are recognised correctly"""

    utc_plus_one = django_timezone.get_fixed_timezone(datetime.timedelta(hours=1))
    now = django_timezone.now()

    def setUp(self):
        super().setUp()
        self._context = warnings.catch_warnings()
        self._context.__enter__()
        warnings.filterwarnings(
            "ignore", message=".*naive datetime", category=RuntimeWarning
        )

    def tearDown(self):
        self._context.__exit__()
        super().tearDown()

    def test_model_with_same_time(self):
        timestamp = datetime.datetime(2017, 1, 10, 12, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)
        dtm = DateTimeFieldModel(
            label="DateTimeField model",
            timestamp=timestamp,
            date=date,
            time=time,
            naive_dt=self.now,
        )
        dtm.save()
        self.assertEqual(dtm.history.count(), 1, msg="There is one log entry")

        # Change timestamp to same datetime and timezone
        timestamp = datetime.datetime(2017, 1, 10, 12, 0, tzinfo=timezone.utc)
        dtm.timestamp = timestamp
        dtm.date = datetime.date(2017, 1, 10)
        dtm.time = datetime.time(12, 0)
        dtm.save()

        # Nothing should have changed
        self.assertEqual(dtm.history.count(), 1, msg="There is one log entry")

    def test_model_with_different_timezone(self):
        timestamp = datetime.datetime(2017, 1, 10, 12, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)
        dtm = DateTimeFieldModel(
            label="DateTimeField model",
            timestamp=timestamp,
            date=date,
            time=time,
            naive_dt=self.now,
        )
        dtm.save()
        self.assertEqual(dtm.history.count(), 1, msg="There is one log entry")

        # Change timestamp to same datetime in another timezone
        timestamp = datetime.datetime(2017, 1, 10, 13, 0, tzinfo=self.utc_plus_one)
        dtm.timestamp = timestamp
        dtm.save()

        # Nothing should have changed
        self.assertEqual(dtm.history.count(), 1, msg="There is one log entry")

    def test_model_with_different_datetime(self):
        timestamp = datetime.datetime(2017, 1, 10, 12, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)
        dtm = DateTimeFieldModel(
            label="DateTimeField model",
            timestamp=timestamp,
            date=date,
            time=time,
            naive_dt=self.now,
        )
        dtm.save()
        self.assertEqual(dtm.history.count(), 1, msg="There is one log entry")

        # Change timestamp to another datetime in the same timezone
        timestamp = datetime.datetime(2017, 1, 10, 13, 0, tzinfo=timezone.utc)
        dtm.timestamp = timestamp
        dtm.save()

        # The time should have changed.
        self.assertEqual(dtm.history.count(), 2, msg="There are two log entries")

    def test_model_with_different_date(self):
        timestamp = datetime.datetime(2017, 1, 10, 12, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)
        dtm = DateTimeFieldModel(
            label="DateTimeField model",
            timestamp=timestamp,
            date=date,
            time=time,
            naive_dt=self.now,
        )
        dtm.save()
        self.assertEqual(dtm.history.count(), 1, msg="There is one log entry")

        # Change timestamp to another datetime in the same timezone
        date = datetime.datetime(2017, 1, 11)
        dtm.date = date
        dtm.save()

        # The time should have changed.
        self.assertEqual(dtm.history.count(), 2, msg="There are two log entries")

    def test_model_with_different_time(self):
        timestamp = datetime.datetime(2017, 1, 10, 12, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)
        dtm = DateTimeFieldModel(
            label="DateTimeField model",
            timestamp=timestamp,
            date=date,
            time=time,
            naive_dt=self.now,
        )
        dtm.save()
        self.assertEqual(dtm.history.count(), 1, msg="There is one log entry")

        # Change timestamp to another datetime in the same timezone
        time = datetime.time(6, 0)
        dtm.time = time
        dtm.save()

        # The time should have changed.
        self.assertEqual(dtm.history.count(), 2, msg="There are two log entries")

    def test_model_with_different_time_and_timezone(self):
        timestamp = datetime.datetime(2017, 1, 10, 12, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)
        dtm = DateTimeFieldModel(
            label="DateTimeField model",
            timestamp=timestamp,
            date=date,
            time=time,
            naive_dt=self.now,
        )
        dtm.save()
        self.assertEqual(dtm.history.count(), 1, msg="There is one log entry")

        # Change timestamp to another datetime and another timezone
        timestamp = datetime.datetime(2017, 1, 10, 14, 0, tzinfo=self.utc_plus_one)
        dtm.timestamp = timestamp
        dtm.save()

        # The time should have changed.
        self.assertEqual(dtm.history.count(), 2, msg="There are two log entries")

    def test_changes_display_dict_datetime(self):
        timestamp = datetime.datetime(2017, 1, 10, 15, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)
        dtm = DateTimeFieldModel(
            label="DateTimeField model",
            timestamp=timestamp,
            date=date,
            time=time,
            naive_dt=self.now,
        )
        dtm.save()
        localized_timestamp = timestamp.astimezone(gettz(settings.TIME_ZONE))
        self.assertEqual(
            dtm.history.latest().changes_display_dict["timestamp"][1],
            dateformat.format(localized_timestamp, settings.DATETIME_FORMAT),
            msg=(
                "The datetime should be formatted according to Django's settings for"
                " DATETIME_FORMAT"
            ),
        )
        timestamp = django_timezone.now()
        dtm.timestamp = timestamp
        dtm.save()
        localized_timestamp = timestamp.astimezone(gettz(settings.TIME_ZONE))
        self.assertEqual(
            dtm.history.latest().changes_display_dict["timestamp"][1],
            dateformat.format(localized_timestamp, settings.DATETIME_FORMAT),
            msg=(
                "The datetime should be formatted according to Django's settings for"
                " DATETIME_FORMAT"
            ),
        )

        # Change USE_L10N = True
        with self.settings(USE_L10N=True, LANGUAGE_CODE="en-GB"):
            self.assertEqual(
                dtm.history.latest().changes_display_dict["timestamp"][1],
                formats.localize(localized_timestamp),
                msg=(
                    "The datetime should be formatted according to Django's settings for"
                    " USE_L10N is True with a different LANGUAGE_CODE."
                ),
            )

    def test_changes_display_dict_date(self):
        timestamp = datetime.datetime(2017, 1, 10, 15, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)
        dtm = DateTimeFieldModel(
            label="DateTimeField model",
            timestamp=timestamp,
            date=date,
            time=time,
            naive_dt=self.now,
        )
        dtm.save()
        self.assertEqual(
            dtm.history.latest().changes_display_dict["date"][1],
            dateformat.format(date, settings.DATE_FORMAT),
            msg=(
                "The date should be formatted according to Django's settings for"
                " DATE_FORMAT unless USE_L10N is True."
            ),
        )
        date = datetime.date(2017, 1, 11)
        dtm.date = date
        dtm.save()
        self.assertEqual(
            dtm.history.latest().changes_display_dict["date"][1],
            dateformat.format(date, settings.DATE_FORMAT),
            msg=(
                "The date should be formatted according to Django's settings for"
                " DATE_FORMAT unless USE_L10N is True."
            ),
        )

        # Change USE_L10N = True
        with self.settings(USE_L10N=True, LANGUAGE_CODE="en-GB"):
            self.assertEqual(
                dtm.history.latest().changes_display_dict["date"][1],
                formats.localize(date),
                msg=(
                    "The date should be formatted according to Django's settings for"
                    " USE_L10N is True with a different LANGUAGE_CODE."
                ),
            )

    def test_changes_display_dict_time(self):
        timestamp = datetime.datetime(2017, 1, 10, 15, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)
        dtm = DateTimeFieldModel(
            label="DateTimeField model",
            timestamp=timestamp,
            date=date,
            time=time,
            naive_dt=self.now,
        )
        dtm.save()
        self.assertEqual(
            dtm.history.latest().changes_display_dict["time"][1],
            dateformat.format(time, settings.TIME_FORMAT),
            msg=(
                "The time should be formatted according to Django's settings for"
                " TIME_FORMAT unless USE_L10N is True."
            ),
        )
        time = datetime.time(6, 0)
        dtm.time = time
        dtm.save()
        self.assertEqual(
            dtm.history.latest().changes_display_dict["time"][1],
            dateformat.format(time, settings.TIME_FORMAT),
            msg=(
                "The time should be formatted according to Django's settings for"
                " TIME_FORMAT unless USE_L10N is True."
            ),
        )

        # Change USE_L10N = True
        with self.settings(USE_L10N=True, LANGUAGE_CODE="en-GB"):
            self.assertEqual(
                dtm.history.latest().changes_display_dict["time"][1],
                formats.localize(time),
                msg=(
                    "The time should be formatted according to Django's settings for"
                    " USE_L10N is True with a different LANGUAGE_CODE."
                ),
            )

    def test_update_naive_dt(self):
        timestamp = datetime.datetime(2017, 1, 10, 15, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)
        dtm = DateTimeFieldModel(
            label="DateTimeField model",
            timestamp=timestamp,
            date=date,
            time=time,
            naive_dt=self.now,
        )
        dtm.save()

        # Change with naive field doesnt raise error
        dtm.naive_dt = django_timezone.make_naive(
            django_timezone.now(), timezone=timezone.utc
        )
        dtm.save()

    def test_datetime_field_functions_now(self):
        timestamp = datetime.datetime(2017, 1, 10, 15, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)

        dtm = DateTimeFieldModel(
            label="DateTimeField model",
            timestamp=timestamp,
            date=date,
            time=time,
            naive_dt=Now(),
        )
        dtm.save()
        dtm.naive_dt = Now()
        self.assertEqual(dtm.naive_dt, Now())
        dtm.save()
        self.assertEqual(dtm.naive_dt, Now())

    def test_json_field_value_none(self):
        json_model = NullableJSONModel(json=Value(None, JSONField()))
        json_model.save()
        self.assertEqual(json_model.history.count(), 1)
        self.assertEqual(
            json_model.history.latest().changes_dict["json"][1], "Value(None)"
        )


class UnregisterTest(TestCase):
    def setUp(self):
        auditlog.unregister(SimpleModel)
        self.obj = SimpleModel.objects.create(text="No history")

    def tearDown(self):
        # Re-register for future tests
        auditlog.register(SimpleModel)

    def test_unregister_create(self):
        """Creation is not logged after unregistering."""
        # Get the object to work with
        obj = self.obj

        # Check for log entries
        self.assertEqual(obj.history.count(), 0, msg="There are no log entries")

    def test_unregister_update(self):
        """Updates are not logged after unregistering."""
        # Get the object to work with
        obj = self.obj

        # Change something
        obj.boolean = True
        obj.save()

        # Check for log entries
        self.assertEqual(obj.history.count(), 0, msg="There are no log entries")

    def test_unregister_delete(self):
        """Deletion is not logged after unregistering."""
        # Get the object to work with
        obj = self.obj

        # Delete the object
        obj.delete()

        # Check for log entries
        self.assertEqual(LogEntry.objects.count(), 0, msg="There are no log entries")

    def test_manual_logging(self):
        obj = self.obj
        obj.boolean = True
        obj.save()
        LogEntry.objects.log_create(
            instance=obj,
            action=LogEntry.Action.UPDATE,
            changes="",
        )
        self.assertEqual(
            obj.history.filter(action=LogEntry.Action.UPDATE).count(),
            1,
            msg="There is one log entry for 'UPDATE'",
        )


class RegisterModelSettingsTest(TestCase):
    def setUp(self):
        self.test_auditlog = AuditlogModelRegistry()

    def tearDown(self):
        for model in self.test_auditlog.get_models():
            self.test_auditlog.unregister(model)

    def test_get_model_classes(self):
        self.assertEqual(
            len(list(self.test_auditlog._get_model_classes("auditlog"))),
            len(list(apps.get_app_config("auditlog").get_models())),
        )
        self.assertEqual([], self.test_auditlog._get_model_classes("fake_model"))

    def test_get_exclude_models(self):
        # By default it returns DEFAULT_EXCLUDE_MODELS
        self.assertEqual(len(self.test_auditlog._get_exclude_models(())), 2)

        # Exclude just one model
        self.assertTrue(
            SimpleExcludeModel
            in self.test_auditlog._get_exclude_models(("test_app.SimpleExcludeModel",))
        )

        # Exclude all model of an app
        self.assertTrue(
            SimpleExcludeModel in self.test_auditlog._get_exclude_models(("test_app",))
        )

    def test_register_models_no_models(self):
        self.test_auditlog._register_models(())

        self.assertEqual(self.test_auditlog._registry, {})

    def test_register_models_register_single_model(self):
        self.test_auditlog._register_models(("test_app.SimpleExcludeModel",))

        self.assertTrue(self.test_auditlog.contains(SimpleExcludeModel))
        self.assertEqual(len(self.test_auditlog._registry), 1)

    def test_register_models_register_app(self):
        self.test_auditlog._register_models(("test_app",))

        self.assertTrue(self.test_auditlog.contains(SimpleExcludeModel))
        self.assertTrue(self.test_auditlog.contains(ChoicesFieldModel))
        self.assertEqual(len(self.test_auditlog.get_models()), 33)

    def test_register_models_register_model_with_attrs(self):
        self.test_auditlog._register_models(
            (
                {
                    "model": "test_app.SimpleExcludeModel",
                    "include_fields": ["label"],
                    "exclude_fields": [
                        "text",
                    ],
                },
            )
        )

        self.assertTrue(self.test_auditlog.contains(SimpleExcludeModel))
        fields = self.test_auditlog.get_model_fields(SimpleExcludeModel)
        self.assertEqual(fields["include_fields"], ["label"])
        self.assertEqual(fields["exclude_fields"], ["text"])

    def test_register_models_register_model_with_m2m_fields(self):
        self.test_auditlog._register_models(
            (
                {
                    "model": "test_app.ManyRelatedModel",
                    "m2m_fields": {"related"},
                },
            )
        )

        self.assertTrue(self.test_auditlog.contains(ManyRelatedModel))
        self.assertEqual(
            self.test_auditlog._registry[ManyRelatedModel]["m2m_fields"], {"related"}
        )

    def test_register_from_settings_invalid_settings(self):
        with override_settings(AUDITLOG_INCLUDE_ALL_MODELS="str"):
            with self.assertRaisesMessage(
                TypeError, "Setting 'AUDITLOG_INCLUDE_ALL_MODELS' must be a boolean"
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(AUDITLOG_EXCLUDE_TRACKING_MODELS="str"):
            with self.assertRaisesMessage(
                TypeError,
                "Setting 'AUDITLOG_EXCLUDE_TRACKING_MODELS' must be a list or tuple",
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(AUDITLOG_EXCLUDE_TRACKING_MODELS=("app1.model1",)):
            with self.assertRaisesMessage(
                ValueError,
                "In order to use setting 'AUDITLOG_EXCLUDE_TRACKING_MODELS', "
                "setting 'AUDITLOG_INCLUDE_ALL_MODELS' must set to 'True'",
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(
            AUDITLOG_INCLUDE_ALL_MODELS=True,
            AUDITLOG_EXCLUDE_TRACKING_FIELDS="badvalue",
        ):
            with self.assertRaisesMessage(
                TypeError,
                "Setting 'AUDITLOG_EXCLUDE_TRACKING_FIELDS' must be a list or tuple",
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(
            AUDITLOG_EXCLUDE_TRACKING_FIELDS=("created", "modified")
        ):
            with self.assertRaisesMessage(
                ValueError,
                "In order to use 'AUDITLOG_EXCLUDE_TRACKING_FIELDS', "
                "setting 'AUDITLOG_INCLUDE_ALL_MODELS' must be set to 'True'",
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(
            AUDITLOG_INCLUDE_ALL_MODELS=True,
            AUDITLOG_MASK_TRACKING_FIELDS="badvalue",
        ):
            with self.assertRaisesMessage(
                TypeError,
                "Setting 'AUDITLOG_MASK_TRACKING_FIELDS' must be a list or tuple",
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(AUDITLOG_MASK_TRACKING_FIELDS=("token", "otp_secret")):
            with self.assertRaisesMessage(
                ValueError,
                "In order to use 'AUDITLOG_MASK_TRACKING_FIELDS', "
                "setting 'AUDITLOG_INCLUDE_ALL_MODELS' must be set to 'True'",
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(AUDITLOG_INCLUDE_TRACKING_MODELS="str"):
            with self.assertRaisesMessage(
                TypeError,
                "Setting 'AUDITLOG_INCLUDE_TRACKING_MODELS' must be a list or tuple",
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(AUDITLOG_INCLUDE_TRACKING_MODELS=(1, 2)):
            with self.assertRaisesMessage(
                TypeError,
                "Setting 'AUDITLOG_INCLUDE_TRACKING_MODELS' items must be str or dict",
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(AUDITLOG_INCLUDE_TRACKING_MODELS=({"test": "test"},)):
            with self.assertRaisesMessage(
                ValueError,
                "Setting 'AUDITLOG_INCLUDE_TRACKING_MODELS' dict items must contain 'model' key",
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(AUDITLOG_INCLUDE_TRACKING_MODELS=({"model": "test"},)):
            with self.assertRaisesMessage(
                ValueError,
                (
                    "Setting 'AUDITLOG_INCLUDE_TRACKING_MODELS' model must be in the "
                    "format <app_name>.<model_name>"
                ),
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(
            AUDITLOG_INCLUDE_TRACKING_MODELS=({"model": "notanapp.test"},)
        ):
            with self.assertRaisesMessage(
                AuditLogRegistrationError,
                (
                    "An error was encountered while registering model 'notanapp.test'"
                    " - make sure the app is registered correctly."
                ),
            ):
                self.test_auditlog.register_from_settings()

        with override_settings(AUDITLOG_DISABLE_ON_RAW_SAVE="bad value"):
            with self.assertRaisesMessage(
                TypeError, "Setting 'AUDITLOG_DISABLE_ON_RAW_SAVE' must be a boolean"
            ):
                self.test_auditlog.register_from_settings()

    @override_settings(
        AUDITLOG_INCLUDE_ALL_MODELS=True,
        AUDITLOG_EXCLUDE_TRACKING_MODELS=("test_app.SimpleExcludeModel",),
    )
    def test_register_from_settings_register_all_models_with_exclude_models_tuple(self):
        self.test_auditlog.register_from_settings()

        self.assertFalse(self.test_auditlog.contains(SimpleExcludeModel))
        self.assertTrue(self.test_auditlog.contains(ChoicesFieldModel))

    @override_settings(
        AUDITLOG_INCLUDE_ALL_MODELS=True,
        AUDITLOG_EXCLUDE_TRACKING_FIELDS=("datetime",),
    )
    def test_register_from_settings_register_all_models_with_exclude_tracking_fields(
        self,
    ):
        self.test_auditlog.register_from_settings()

        self.assertEqual(
            self.test_auditlog.get_model_fields(SimpleModel)["exclude_fields"],
            ["datetime"],
        )
        self.assertEqual(
            self.test_auditlog.get_model_fields(AltPrimaryKeyModel)["exclude_fields"],
            ["datetime"],
        )

    @override_settings(
        AUDITLOG_INCLUDE_ALL_MODELS=True,
        AUDITLOG_MASK_TRACKING_FIELDS=("secret",),
    )
    def test_register_from_settings_register_all_models_with_mask_tracking_fields(
        self,
    ):
        self.test_auditlog.register_from_settings()

        self.assertEqual(
            self.test_auditlog.get_model_fields(SimpleModel)["mask_fields"],
            ["secret"],
        )
        self.assertEqual(
            self.test_auditlog.get_model_fields(AltPrimaryKeyModel)["mask_fields"],
            ["secret"],
        )

    @override_settings(
        AUDITLOG_INCLUDE_ALL_MODELS=True,
        AUDITLOG_EXCLUDE_TRACKING_MODELS=["test_app.SimpleExcludeModel"],
    )
    def test_register_from_settings_register_all_models_with_exclude_models_list(self):
        self.test_auditlog.register_from_settings()

        self.assertFalse(self.test_auditlog.contains(SimpleExcludeModel))
        self.assertTrue(self.test_auditlog.contains(ChoicesFieldModel))

    @override_settings(
        AUDITLOG_INCLUDE_TRACKING_MODELS=(
            {
                "model": "test_app.SimpleExcludeModel",
                "include_fields": ["label"],
                "exclude_fields": [
                    "text",
                ],
            },
        )
    )
    def test_register_from_settings_register_models(self):
        self.test_auditlog.register_from_settings()

        self.assertTrue(self.test_auditlog.contains(SimpleExcludeModel))
        fields = self.test_auditlog.get_model_fields(SimpleExcludeModel)
        self.assertEqual(fields["include_fields"], ["label"])
        self.assertEqual(fields["exclude_fields"], ["text"])

    def test_registration_error_if_bad_serialize_params(self):
        with self.assertRaisesMessage(
            AuditLogRegistrationError,
            "Serializer options were given but the 'serialize_data' option is not "
            "set. Did you forget to set serialized_data to True?",
        ):
            register = AuditlogModelRegistry()
            register.register(
                SimpleModel, serialize_kwargs={"fields": ["text", "integer"]}
            )

    @override_settings(AUDITLOG_INCLUDE_ALL_MODELS=True)
    def test_register_from_settings_register_all_models_excluding_non_managed_models(
        self,
    ):
        self.test_auditlog.register_from_settings()

        self.assertFalse(self.test_auditlog.contains(SimpleNonManagedModel))

    @override_settings(AUDITLOG_INCLUDE_ALL_MODELS=True)
    def test_register_from_settings_register_all_models_and_figure_out_m2m_fields(self):
        self.test_auditlog.register_from_settings()

        self.assertIn(
            "related", self.test_auditlog._registry[AutoManyRelatedModel]["m2m_fields"]
        )

    @override_settings(AUDITLOG_INCLUDE_ALL_MODELS=True)
    def test_register_from_settings_register_all_models_including_auto_created_models(
        self,
    ):
        self.test_auditlog.register_from_settings()

        self.assertTrue(
            self.test_auditlog.contains(AutoManyRelatedModel.related.through)
        )


class ChoicesFieldModelTest(TestCase):
    def setUp(self):
        self.obj = ChoicesFieldModel.objects.create(
            status=ChoicesFieldModel.RED,
            multiplechoice=[
                ChoicesFieldModel.RED,
                ChoicesFieldModel.YELLOW,
                ChoicesFieldModel.GREEN,
            ],
        )

    def test_changes_display_dict_single_choice(self):
        self.assertEqual(
            self.obj.history.latest().changes_display_dict["status"][1],
            "Red",
            msg="The human readable text 'Red' is displayed.",
        )
        self.obj.status = ChoicesFieldModel.GREEN
        self.obj.save()
        self.assertEqual(
            self.obj.history.latest().changes_display_dict["status"][1],
            "Green",
            msg="The human readable text 'Green' is displayed.",
        )

    def test_changes_display_dict_multiplechoice(self):
        self.assertEqual(
            self.obj.history.latest().changes_display_dict["multiplechoice"][1],
            "Red, Yellow, Green",
            msg="The human readable text 'Red, Yellow, Green' is displayed.",
        )
        self.obj.multiplechoice = ChoicesFieldModel.RED
        self.obj.save()
        self.assertEqual(
            self.obj.history.latest().changes_display_dict["multiplechoice"][1],
            "Red",
            msg="The human readable text 'Red' is displayed.",
        )

    def test_changes_display_dict_many_to_one_relation(self):
        obj = SimpleModel()
        obj.save()
        history = obj.history.get()
        assert "related_models" in history.changes_display_dict


class CharFieldTextFieldModelTest(TestCase):
    def setUp(self):
        self.PLACEHOLDER_LONGCHAR = "s" * 255
        self.PLACEHOLDER_LONGTEXTFIELD = "s" * 1000
        self.obj = CharfieldTextfieldModel.objects.create(
            longchar=self.PLACEHOLDER_LONGCHAR,
            longtextfield=self.PLACEHOLDER_LONGTEXTFIELD,
        )

    def test_changes_display_dict_longchar(self):
        self.assertEqual(
            self.obj.history.latest().changes_display_dict["longchar"][1],
            f"{self.PLACEHOLDER_LONGCHAR[:140]}...",
            msg="The string should be truncated at 140 characters with an ellipsis at the end.",
        )
        SHORTENED_PLACEHOLDER = self.PLACEHOLDER_LONGCHAR[:139]
        self.obj.longchar = SHORTENED_PLACEHOLDER
        self.obj.save()
        self.assertEqual(
            self.obj.history.latest().changes_display_dict["longchar"][1],
            SHORTENED_PLACEHOLDER,
            msg="The field should display the entire string because it is less than 140 characters",
        )

    def test_changes_display_dict_longtextfield(self):
        self.assertEqual(
            self.obj.history.latest().changes_display_dict["longtextfield"][1],
            f"{self.PLACEHOLDER_LONGTEXTFIELD[:140]}...",
            msg="The string should be truncated at 140 characters with an ellipsis at the end.",
        )
        SHORTENED_PLACEHOLDER = self.PLACEHOLDER_LONGTEXTFIELD[:139]
        self.obj.longtextfield = SHORTENED_PLACEHOLDER
        self.obj.save()
        self.assertEqual(
            self.obj.history.latest().changes_display_dict["longtextfield"][1],
            SHORTENED_PLACEHOLDER,
            msg="The field should display the entire string because it is less than 140 characters",
        )

    def test_changes_display_dict_longtextfield_to_be_truncated_at_custom_length(self):
        with override_settings(AUDITLOG_CHANGE_DISPLAY_TRUNCATE_LENGTH=10):
            length = settings.AUDITLOG_CHANGE_DISPLAY_TRUNCATE_LENGTH
            self.assertEqual(
                self.obj.history.latest().changes_display_dict["longtextfield"][1],
                f"{self.PLACEHOLDER_LONGCHAR[:length]}...",
                msg=f"The string should be truncated at {length} characters with an ellipsis at the end.",
            )

    def test_changes_display_dict_longtextfield_to_be_truncated_to_empty_string(self):
        with override_settings(AUDITLOG_CHANGE_DISPLAY_TRUNCATE_LENGTH=0):
            length = settings.AUDITLOG_CHANGE_DISPLAY_TRUNCATE_LENGTH
            self.assertEqual(
                self.obj.history.latest().changes_display_dict["longtextfield"][1],
                "",
                msg=f"The string should be empty as AUDITLOG_TRUNCATE_CHANGES_DISPLAY is set to {length}.",
            )

    def test_changes_display_dict_longtextfield_with_truncation_disabled(self):
        with override_settings(AUDITLOG_CHANGE_DISPLAY_TRUNCATE_LENGTH=-1):
            length = settings.AUDITLOG_CHANGE_DISPLAY_TRUNCATE_LENGTH
            self.assertEqual(
                self.obj.history.latest().changes_display_dict["longtextfield"][1],
                self.PLACEHOLDER_LONGTEXTFIELD,
                msg=(
                    "The field should display the entire string "
                    f"even though it is longer than {length} characters"
                    "as AUDITLOG_TRUNCATE_CHANGES_DISPLAY is set to a negative number"
                ),
            )


class PostgresArrayFieldModelTest(TestCase):
    databases = "__all__"

    def setUp(self):
        self.obj = PostgresArrayFieldModel.objects.create(
            arrayfield=[PostgresArrayFieldModel.RED, PostgresArrayFieldModel.GREEN],
        )

    @property
    def latest_array_change(self):
        return self.obj.history.latest().changes_display_dict["arrayfield"][1]

    def test_changes_display_dict_arrayfield(self):
        self.assertEqual(
            self.latest_array_change,
            "Red, Green",
            msg="The human readable text for the two choices, 'Red, Green' is displayed.",
        )
        self.obj.arrayfield = [PostgresArrayFieldModel.GREEN]
        self.obj.save()
        self.assertEqual(
            self.latest_array_change,
            "Green",
            msg="The human readable text 'Green' is displayed.",
        )
        self.obj.arrayfield = []
        self.obj.save()
        self.assertEqual(
            self.latest_array_change,
            "",
            msg="The human readable text '' is displayed.",
        )
        self.obj.arrayfield = [PostgresArrayFieldModel.GREEN]
        self.obj.save()
        self.assertEqual(
            self.latest_array_change,
            "Green",
            msg="The human readable text 'Green' is displayed.",
        )


class AdminPanelTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username="test_admin", is_staff=True, is_superuser=True, is_active=True
        )
        self.site = AdminSite()
        self.admin = LogEntryAdmin(LogEntry, self.site)
        with freezegun.freeze_time("2022-08-01 12:00:00Z"):
            self.obj = SimpleModel.objects.create(text="For admin logentry test")

    def test_auditlog_admin(self):
        self.client.force_login(self.user)
        log_pk = self.obj.history.latest().pk
        res = self.client.get("/admin/auditlog/logentry/")
        self.assertEqual(res.status_code, 200)
        res = self.client.get("/admin/auditlog/logentry/add/")
        self.assertEqual(res.status_code, 403)
        res = self.client.get(f"/admin/auditlog/logentry/{log_pk}/", follow=True)
        self.assertEqual(res.status_code, 200)
        res = self.client.get(f"/admin/auditlog/logentry/{log_pk}/delete/")
        self.assertEqual(res.status_code, 403)
        res = self.client.get(f"/admin/auditlog/logentry/{log_pk}/history/")
        self.assertEqual(res.status_code, 200)

    def test_created_timezone(self):
        log_entry = self.obj.history.latest()

        for tz, timestamp in [
            ("UTC", "2022-08-01 12:00:00"),
            ("Asia/Tbilisi", "2022-08-01 16:00:00"),
            ("America/Buenos_Aires", "2022-08-01 09:00:00"),
            ("Asia/Kathmandu", "2022-08-01 17:45:00"),
        ]:
            with self.settings(TIME_ZONE=tz):
                created = self.admin.created(log_entry)
                self.assertEqual(created.strftime("%Y-%m-%d %H:%M:%S"), timestamp)

    @freezegun.freeze_time("2022-08-01 12:00:00Z")
    def test_created_naive_datetime(self):
        with self.settings(USE_TZ=False):
            obj = SimpleModel.objects.create(text="For USE_TZ=False test")
            log_entry = obj.history.latest()
            created = self.admin.created(log_entry)
            self.assertEqual(
                created.strftime("%Y-%m-%d %H:%M:%S"),
                "2022-08-01 12:00:00",
            )

    def test_cid(self):
        self.client.force_login(self.user)
        expected_response = (
            '<a href="/admin/auditlog/logentry/?cid=123" '
            'title="Click to filter by records with this correlation id">123</a>'
        )

        log_entry = self.obj.history.latest()
        log_entry.cid = "123"
        log_entry.save()

        res = self.client.get("/admin/auditlog/logentry/")
        self.assertEqual(res.status_code, 200)
        self.assertIn(expected_response, res.rendered_content)

    def test_has_delete_permission(self):
        log = self.obj.history.latest()
        obj_pk = self.obj.pk
        delete_log_request = RequestFactory().post(
            f"/admin/auditlog/logentry/{log.pk}/delete/"
        )
        delete_log_request.resolver_match = resolve(delete_log_request.path)
        delete_log_request.user = self.user
        delete_object_request = RequestFactory().post(
            f"/admin/tests/simplemodel/{obj_pk}/delete/"
        )
        delete_object_request.resolver_match = resolve(delete_object_request.path)
        delete_object_request.user = self.user

        self.assertTrue(self.admin.has_delete_permission(delete_object_request, log))
        self.assertFalse(self.admin.has_delete_permission(delete_log_request, log))


class DiffMsgTest(TestCase):
    def setUp(self):
        super().setUp()
        self.site = AdminSite()
        self.admin = LogEntryAdmin(LogEntry, self.site)

    def _create_log_entry(self, action, changes):
        return LogEntry.objects.log_create(
            SimpleModel.objects.create(),  # doesn't affect anything
            action=action,
            changes=changes,
        )

    def test_change_msg_create_when_exceeds_max_len(self):
        log_entry = self._create_log_entry(
            LogEntry.Action.CREATE,
            {
                "Camelopardalis": [None, "Giraffe"],
                "Capricornus": [None, "Sea goat"],
                "Equuleus": [None, "Little horse"],
                "Horologium": [None, "Clock"],
                "Microscopium": [None, "Microscope"],
                "Reticulum": [None, "Net"],
                "Telescopium": [None, "Telescope"],
            },
        )

        self.assertEqual(
            self.admin.msg_short(log_entry),
            "7 changes: Camelopardalis, Capricornus, Equuleus, Horologium, "
            "Microscopium, ..",
        )

    def test_changes_msg_delete(self):
        log_entry = self._create_log_entry(
            LogEntry.Action.DELETE,
            {"field one": ["value before deletion", None], "field two": [11, None]},
        )

        self.assertEqual(self.admin.msg_short(log_entry), "")
        self.assertEqual(
            self.admin.msg(log_entry),
            (
                "<table>"
                "<tr><th>#</th><th>Field</th><th>From</th><th>To</th></tr>"
                "<tr><td>1</td><td>Field one</td><td>value before deletion</td><td>None</td></tr>"
                "<tr><td>2</td><td>Field two</td><td>11</td><td>None</td></tr>"
                "</table>"
            ),
        )

    def test_instance_translation_and_history_logging(self):
        first = SimpleModel()
        second = SimpleModel(text=_("test"))
        changes = model_instance_diff(first, second)
        self.assertEqual(changes, {"text": ("", "test")})
        second.save()
        log_one = second.history.last()
        self.assertTrue(isinstance(log_one, LogEntry))

    def test_changes_msg_create(self):
        log_entry = self._create_log_entry(
            LogEntry.Action.CREATE,
            {
                "field two": [None, 11],
                "field one": [None, "a value"],
            },
        )

        self.assertEqual(
            self.admin.msg_short(log_entry), "2 changes: field two, field one"
        )
        self.assertEqual(
            self.admin.msg(log_entry),
            (
                "<table>"
                "<tr><th>#</th><th>Field</th><th>From</th><th>To</th></tr>"
                "<tr><td>1</td><td>Field one</td><td>None</td><td>a value</td></tr>"
                "<tr><td>2</td><td>Field two</td><td>None</td><td>11</td></tr>"
                "</table>"
            ),
        )

    def test_changes_msg_update(self):
        log_entry = self._create_log_entry(
            LogEntry.Action.UPDATE,
            {
                "field two": [11, 42],
                "field one": ["old value of field one", "new value of field one"],
            },
        )

        self.assertEqual(
            self.admin.msg_short(log_entry), "2 changes: field two, field one"
        )
        self.assertEqual(
            self.admin.msg(log_entry),
            (
                "<table>"
                "<tr><th>#</th><th>Field</th><th>From</th><th>To</th></tr>"
                "<tr><td>1</td><td>Field one</td><td>old value of field one</td>"
                "<td>new value of field one</td></tr>"
                "<tr><td>2</td><td>Field two</td><td>11</td><td>42</td></tr>"
                "</table>"
            ),
        )

    def test_changes_msg_m2m(self):
        log_entry = self._create_log_entry(
            LogEntry.Action.UPDATE,
            {  # mimicking the format used by log_m2m_changes
                "some_m2m_field": {
                    "type": "m2m",
                    "operation": "add",
                    "objects": ["Example User (user 1)", "Illustration (user 42)"],
                },
            },
        )

        self.assertEqual(self.admin.msg_short(log_entry), "1 change: some_m2m_field")
        self.assertEqual(
            self.admin.msg(log_entry),
            (
                "<table>"
                "<tr><th>#</th><th>Relationship</th><th>Action</th><th>Objects</th></tr>"
                "<tr><td>1</td><td>Some m2m field</td><td>add</td><td>Example User (user 1)"
                "<br>Illustration (user 42)</td></tr>"
                "</table>"
            ),
        )

    def test_unregister_after_log(self):
        log_entry = self._create_log_entry(
            LogEntry.Action.CREATE,
            {
                "field two": [None, 11],
                "field one": [None, "a value"],
            },
        )
        # Unregister
        auditlog.unregister(SimpleModel)
        self.assertEqual(
            self.admin.msg_short(log_entry), "2 changes: field two, field one"
        )
        self.assertEqual(
            self.admin.msg(log_entry),
            (
                "<table>"
                "<tr><th>#</th><th>Field</th><th>From</th><th>To</th></tr>"
                "<tr><td>1</td><td>Field one</td><td>None</td><td>a value</td></tr>"
                "<tr><td>2</td><td>Field two</td><td>None</td><td>11</td></tr>"
                "</table>"
            ),
        )
        # Re-register
        auditlog.register(SimpleModel)

    def test_field_verbose_name(self):
        log_entry = self._create_log_entry(
            LogEntry.Action.CREATE,
            {"test": "test"},
        )

        self.assertEqual(self.admin.field_verbose_name(log_entry, "actor"), "Actor")
        with patch(
            "django.contrib.contenttypes.models.ContentType.model_class",
            return_value=None,
        ):
            self.assertEqual(self.admin.field_verbose_name(log_entry, "actor"), "actor")


class NoDeleteHistoryTest(TestCase):
    def test_delete_related(self):
        instance = SimpleModel.objects.create(integer=1)
        assert LogEntry.objects.all().count() == 1
        instance.integer = 2
        instance.save()
        assert LogEntry.objects.all().count() == 2

        instance.delete()
        entries = LogEntry.objects.order_by("id")

        # The "DELETE" record is always retained
        assert LogEntry.objects.all().count() == 1
        assert entries.first().action == LogEntry.Action.DELETE

    def test_no_delete_related(self):
        instance = NoDeleteHistoryModel.objects.create(integer=1)
        self.assertEqual(LogEntry.objects.all().count(), 1)
        instance.integer = 2
        instance.save()
        self.assertEqual(LogEntry.objects.all().count(), 2)

        instance.delete()
        entries = LogEntry.objects.order_by("id")
        self.assertEqual(entries.count(), 3)
        self.assertEqual(
            list(entries.values_list("action", flat=True)),
            [LogEntry.Action.CREATE, LogEntry.Action.UPDATE, LogEntry.Action.DELETE],
        )


class JSONModelTest(TestCase):
    def setUp(self):
        self.obj = JSONModel.objects.create()

    def test_update(self):
        """Changes on a JSONField are logged correctly."""
        # Get the object to work with
        obj = self.obj

        # Change something
        obj.json = {
            "quantity": "1",
        }
        obj.save()

        # Check for log entries
        self.assertEqual(
            obj.history.filter(action=LogEntry.Action.UPDATE).count(),
            1,
            msg="There is one log entry for 'UPDATE'",
        )

        history = obj.history.get(action=LogEntry.Action.UPDATE)

        self.assertDictEqual(
            history.changes,
            {"json": ["{}", '{"quantity": "1"}']},
            msg="The change is correctly logged",
        )

    def test_update_with_no_changes(self):
        """No changes are logged."""
        first_json = {
            "quantity": "1814",
            "tax_rate": "17",
            "unit_price": "144",
            "description": "Method form.",
            "discount_rate": "42",
            "unit_of_measure": "bytes",
        }
        obj = JSONModel.objects.create(json=first_json)

        # Change the order of the keys but not the values
        second_json = {
            "tax_rate": "17",
            "description": "Method form.",
            "quantity": "1814",
            "unit_of_measure": "bytes",
            "unit_price": "144",
            "discount_rate": "42",
        }
        obj.json = second_json
        obj.save()

        # Check for log entries
        self.assertEqual(
            first_json,
            second_json,
            msg="dicts are the same",
        )
        self.assertEqual(
            obj.history.filter(action=LogEntry.Action.UPDATE).count(),
            0,
            msg="There is no log entry",
        )


class ModelInstanceDiffTest(TestCase):
    def test_diff_models_with_related_fields(self):
        """No error is raised when comparing models with related fields."""

        # This tests that track_field() does indeed ignore related fields.

        # a model without reverse relations
        simple1 = SimpleModel()
        simple1.save()

        # a model with reverse relations
        simple2 = SimpleModel()
        simple2.save()
        related = RelatedModel(related=simple2, one_to_one=simple2)
        related.save()

        # Demonstrate that simple1 can have DoesNotExist on reverse
        # OneToOne relation.
        with self.assertRaises(
            SimpleModel.reverse_one_to_one.RelatedObjectDoesNotExist
        ):
            simple1.reverse_one_to_one  # equals None

        # accessing relatedmodel_set won't trigger DoesNotExist.
        self.assertEqual(simple1.related_models.count(), 0)

        # simple2 DOES have these relations
        self.assertEqual(simple2.reverse_one_to_one, related)
        self.assertEqual(simple2.related_models.count(), 1)

        model_instance_diff(simple2, simple1)
        model_instance_diff(simple1, simple2)

    def test_object_repr_related_deleted(self):
        """No error is raised when __str__() loads a related object that has been deleted."""
        simple = SimpleModel()
        simple.save()
        related = RelatedModel(related=simple, one_to_one=simple)
        related.save()
        related_id = related.id

        related.refresh_from_db()
        simple.delete()
        related.delete()

        log_entry = (
            LogEntry.objects.get_for_model(RelatedModel)
            .filter(object_id=related_id)
            .get(action=LogEntry.Action.DELETE)
        )
        self.assertEqual(log_entry.object_repr, DEFAULT_OBJECT_REPR)

    def test_when_field_doesnt_exist(self):
        """No error is raised and the default is returned."""
        first = SimpleModel(boolean=True)
        second = SimpleModel()

        # then boolean should be False, as we use the default value
        # specified inside the model
        del second.boolean

        changes = model_instance_diff(first, second)

        # Check for log entries
        self.assertEqual(
            changes,
            {"boolean": ("True", "False")},
            msg="ObjectDoesNotExist should be handled",
        )

    def test_field_with_no_default_provided(self):
        """Field with no default (NOT_PROVIDED) should return None."""
        first = SimpleModel(integer=1)
        second = SimpleModel()

        delattr(second, "integer")

        changes = model_instance_diff(first, second)
        self.assertEqual(
            changes,
            {"integer": ("1", "None")},
            msg="field with no default should return None",
        )

    def test_field_with_callable_default(self):
        first = SimpleModel(char="value")
        second = SimpleModel()

        delattr(second, "char")

        changes = model_instance_diff(first, second)
        self.assertEqual(
            changes,
            {"char": ("value", "default value")},
            msg="callable default should be handled",
        )

    def test_diff_models_with_json_fields(self):
        first = JSONModel.objects.create(
            json={
                "code": "17",
                "date": datetime.date(2022, 1, 1),
                "description": "first",
            }
        )
        first.refresh_from_db()  # refresh json data from db
        second = JSONModel.objects.create(
            json={
                "code": "17",
                "description": "second",
                "date": datetime.date(2023, 1, 1),
            }
        )
        diff = model_instance_diff(first, second, ["json"])

        self.assertDictEqual(
            diff,
            {
                "json": (
                    '{"code": "17", "date": "2022-01-01", "description": "first"}',
                    '{"code": "17", "date": "2023-01-01", "description": "second"}',
                )
            },
        )


class TestRelatedDiffs(TestCase):
    def setUp(self):
        self.test_date = datetime.datetime(2022, 1, 1, 12, tzinfo=datetime.timezone.utc)

    def test_log_entry_changes_on_fk_object_update(self):
        t1 = self.test_date
        with freezegun.freeze_time(t1):
            simple = SimpleModel.objects.create()
            one_simple = SimpleModel.objects.create()
            two_simple = SimpleModel.objects.create()
            instance = RelatedModel.objects.create(
                one_to_one=simple, related=one_simple
            )

        t2 = self.test_date + datetime.timedelta(days=20)
        with freezegun.freeze_time(t2):
            instance.related = two_simple
            instance.save()

        log_one = instance.history.filter(timestamp=t1).first()
        log_two = instance.history.filter(timestamp=t2).first()
        self.assertTrue(isinstance(log_one, LogEntry))
        self.assertTrue(isinstance(log_two, LogEntry))

        self.assertEqual(int(log_one.changes_dict["related"][1]), one_simple.id)
        self.assertEqual(int(log_one.changes_dict["one_to_one"][1]), simple.id)
        self.assertEqual(int(log_two.changes_dict["related"][1]), two_simple.id)

    def test_log_entry_changes_on_fk_object_id_update(self):
        t1 = self.test_date
        with freezegun.freeze_time(t1):
            simple = SimpleModel.objects.create()
            one_simple = SimpleModel.objects.create()
            two_simple = SimpleModel.objects.create()
            instance = RelatedModel.objects.create(
                one_to_one=simple, related=one_simple
            )

        t2 = self.test_date + datetime.timedelta(days=20)
        with freezegun.freeze_time(t2):
            instance.related_id = two_simple.id
            instance.one_to_one = one_simple
            instance.save(update_fields=["related_id", "one_to_one_id"])

        log_one = instance.history.filter(timestamp=t1).first()
        log_two = instance.history.filter(timestamp=t2).first()
        self.assertTrue(isinstance(log_one, LogEntry))
        self.assertTrue(isinstance(log_two, LogEntry))

        self.assertEqual(int(log_one.changes_dict["related"][1]), one_simple.id)
        self.assertEqual(int(log_one.changes_dict["one_to_one"][1]), simple.id)
        self.assertEqual(int(log_two.changes_dict["related"][1]), two_simple.id)
        self.assertEqual(int(log_two.changes_dict["one_to_one"][1]), one_simple.id)

    def test_log_entry_changes_on_fk_id_update(self):
        t1 = self.test_date
        with freezegun.freeze_time(t1):
            simple = SimpleModel.objects.create()
            one_simple = SimpleModel.objects.create()
            two_simple = SimpleModel.objects.create()
            instance = RelatedModel.objects.create(
                one_to_one_id=int(simple.id), related_id=int(one_simple.id)
            )

        t2 = self.test_date + datetime.timedelta(days=20)
        with freezegun.freeze_time(t2):
            instance.related_id = int(two_simple.id)
            instance.save()

        log_one = instance.history.filter(timestamp=t1).first()
        log_two = instance.history.filter(timestamp=t2).first()
        self.assertTrue(isinstance(log_one, LogEntry))
        self.assertTrue(isinstance(log_two, LogEntry))

        self.assertEqual(int(log_one.changes_dict["related"][1]), one_simple.id)
        self.assertEqual(int(log_one.changes_dict["one_to_one"][1]), simple.id)
        self.assertEqual(int(log_two.changes_dict["related"][1]), two_simple.id)

    def test_log_entry_create_fk_changes_to_string_objects_in_display_dict(self):
        t1 = self.test_date
        with freezegun.freeze_time(t1):
            simple = SimpleModel.objects.create(text="Test Foo")
            one_simple = SimpleModel.objects.create(text="Test Bar")
            instance = RelatedModel.objects.create(
                one_to_one=simple, related=one_simple
            )

        log_one = instance.history.filter(timestamp=t1).first()
        self.assertTrue(isinstance(log_one, LogEntry))
        display_dict = log_one.changes_display_dict
        self.assertEqual(display_dict["related"][1], "Test Bar")
        self.assertEqual(display_dict["related"][0], "None")
        self.assertEqual(display_dict["one to one"][1], "Test Foo")

    def test_log_entry_deleted_fk_changes_to_string_objects_in_display_dict(self):
        t1 = self.test_date
        with freezegun.freeze_time(t1):
            simple = SimpleModel.objects.create(text="Test Foo")
            one_simple = SimpleModel.objects.create(text="Test Bar")
            one_simple_id = int(one_simple.id)
            instance = RelatedModel.objects.create(
                one_to_one=simple, related=one_simple
            )

        t2 = self.test_date + datetime.timedelta(days=20)
        with freezegun.freeze_time(t2):
            one_simple.delete()

        log_two = LogEntry.objects.filter(object_id=instance.id, timestamp=t2).first()
        self.assertTrue(isinstance(log_two, LogEntry))
        display_dict = log_two.changes_display_dict
        self.assertEqual(
            display_dict["related"][0], f"Deleted 'SimpleModel' ({one_simple_id})"
        )
        self.assertEqual(display_dict["related"][1], "None")

    def test_no_log_entry_created_on_related_object_string_update(self):
        t1 = self.test_date
        with freezegun.freeze_time(t1):
            simple = SimpleModel.objects.create(text="Test Foo")
            one_simple = SimpleModel.objects.create(text="Test Bar")
            instance = RelatedModel.objects.create(
                one_to_one=simple, related=one_simple
            )

        t2 = self.test_date + datetime.timedelta(days=20)
        with freezegun.freeze_time(t2):
            # Order is important. Without special FK handling, the arbitrary in memory
            # changes to the (same) related object's signature result in a perceived
            # update where no update has occurred.
            one_simple.text = "Test Baz"
            instance.save()
            one_simple.save()

        # Assert that only one log for the instance was created
        self.assertEqual(instance.history.all().count(), 1)
        # Assert that two logs were created for the parent object
        self.assertEqual(one_simple.history.all().count(), 2)

    def test_log_entry_created_if_obj_strings_are_same_for_two_objs(self):
        """FK changes trigger update when the string representation is the same."""
        t1 = self.test_date
        with freezegun.freeze_time(t1):
            simple = SimpleModel.objects.create(text="Test Foo")
            one_simple = SimpleModel.objects.create(text="Twinsies", boolean=True)
            two_simple = SimpleModel.objects.create(text="Twinsies", boolean=False)
            instance = RelatedModel.objects.create(
                one_to_one=simple, related=one_simple
            )

        t2 = self.test_date + datetime.timedelta(days=20)
        with freezegun.freeze_time(t2):
            instance.related = two_simple
            instance.save()

        self.assertEqual(instance.history.all().count(), 2)
        log_create = instance.history.filter(timestamp=t1).first()
        log_update = instance.history.filter(timestamp=t2).first()
        self.assertEqual(int(log_create.changes_dict["related"][1]), one_simple.id)
        self.assertEqual(int(log_update.changes_dict["related"][1]), two_simple.id)


class TestModelSerialization(TestCase):
    def setUp(self):
        super().setUp()
        self.test_date = datetime.datetime(2022, 1, 1, 12, tzinfo=timezone.utc)
        self.test_date_string = datetime.datetime.strftime(
            self.test_date, "%Y-%m-%dT%XZ"
        )

    def test_does_not_serialize_data_when_not_configured(self):
        instance = SimpleModel.objects.create(
            text="sample text here", boolean=True, integer=4
        )

        log = instance.history.first()
        self.assertIsNone(log.serialized_data)

    def test_serializes_data_on_create(self):
        with freezegun.freeze_time(self.test_date):
            instance = SerializeThisModel.objects.create(
                label="test label",
                timestamp=self.test_date,
                nullable=4,
                nested={"foo": True, "bar": False},
            )

        log = instance.history.first()
        self.assertTrue(isinstance(log, LogEntry))
        self.assertEqual(log.action, 0)
        self.assertDictEqual(
            log.serialized_data["fields"],
            {
                "label": "test label",
                "timestamp": self.test_date_string,
                "nullable": 4,
                "nested": {"foo": True, "bar": False},
                "mask_me": None,
                "date": None,
                "code": None,
            },
        )

    def test_serializes_data_on_update(self):
        with freezegun.freeze_time(self.test_date):
            instance = SerializeThisModel.objects.create(
                label="test label",
                timestamp=self.test_date,
                nullable=4,
                nested={"foo": True, "bar": False},
            )

        update_date = self.test_date + datetime.timedelta(days=4)
        with freezegun.freeze_time(update_date):
            instance.label = "test label change"
            instance.save()

        log = instance.history.filter(timestamp=update_date).first()
        self.assertTrue(isinstance(log, LogEntry))
        self.assertEqual(log.action, 1)
        self.assertDictEqual(
            log.serialized_data["fields"],
            {
                "label": "test label change",
                "timestamp": self.test_date_string,
                "nullable": 4,
                "nested": {"foo": True, "bar": False},
                "mask_me": None,
                "date": None,
                "code": None,
            },
        )

    def test_serializes_data_on_delete(self):
        with freezegun.freeze_time(self.test_date):
            instance = SerializeThisModel.objects.create(
                label="test label",
                timestamp=self.test_date,
                nullable=4,
                nested={"foo": True, "bar": False},
            )

        obj_id = int(instance.id)
        delete_date = self.test_date + datetime.timedelta(days=4)
        with freezegun.freeze_time(delete_date):
            instance.delete()

        log = LogEntry.objects.filter(object_id=obj_id, timestamp=delete_date).first()
        self.assertTrue(isinstance(log, LogEntry))
        self.assertEqual(log.action, 2)
        self.assertDictEqual(
            log.serialized_data["fields"],
            {
                "label": "test label",
                "timestamp": self.test_date_string,
                "nullable": 4,
                "nested": {"foo": True, "bar": False},
                "mask_me": None,
                "date": None,
                "code": None,
            },
        )

    def test_serialize_string_representations(self):
        with freezegun.freeze_time(self.test_date):
            instance = SerializeThisModel.objects.create(
                label="test label",
                nullable=4,
                nested={"foo": 10, "bar": False},
                timestamp="2022-03-01T12:00Z",
                date="2022-04-05",
                code="e82d5e53-ca80-4037-af55-b90752326460",
            )

        log = instance.history.first()
        self.assertTrue(isinstance(log, LogEntry))
        self.assertEqual(log.action, 0)
        self.assertDictEqual(
            log.serialized_data["fields"],
            {
                "label": "test label",
                "timestamp": "2022-03-01T12:00:00Z",
                "date": "2022-04-05",
                "code": "e82d5e53-ca80-4037-af55-b90752326460",
                "nullable": 4,
                "nested": {"foo": 10, "bar": False},
                "mask_me": None,
            },
        )

    def test_serialize_mask_fields(self):
        with freezegun.freeze_time(self.test_date):
            instance = SerializeThisModel.objects.create(
                label="test label",
                nullable=4,
                timestamp=self.test_date,
                nested={"foo": 10, "bar": False},
                mask_me="confidential",
            )

        log = instance.history.first()
        self.assertTrue(isinstance(log, LogEntry))
        self.assertEqual(log.action, 0)
        self.assertDictEqual(
            log.serialized_data["fields"],
            {
                "label": "test label",
                "timestamp": self.test_date_string,
                "nullable": 4,
                "nested": {"foo": 10, "bar": False},
                "mask_me": "******ential",
                "date": None,
                "code": None,
            },
        )

    def test_serialize_only_auditlog_fields(self):
        with freezegun.freeze_time(self.test_date):
            instance = SerializeOnlySomeOfThisModel.objects.create(
                this="this should be there", not_this="leave this bit out"
            )

        log = instance.history.first()
        self.assertTrue(isinstance(log, LogEntry))
        self.assertEqual(log.action, 0)
        self.assertDictEqual(
            log.serialized_data["fields"], {"this": "this should be there"}
        )
        self.assertDictEqual(
            log.changes_dict,
            {"this": ["None", "this should be there"], "id": ["None", "1"]},
        )

    def test_serialize_related(self):
        with freezegun.freeze_time(self.test_date):
            serialize_this = SerializeThisModel.objects.create(
                label="test label",
                nested={"foo": "bar"},
                timestamp=self.test_date,
            )
            instance = SerializePrimaryKeyRelatedModel.objects.create(
                serialize_this=serialize_this,
                subheading="use a primary key for this serialization, please.",
                value=10,
            )

        log = instance.history.first()
        self.assertTrue(isinstance(log, LogEntry))
        self.assertEqual(log.action, 0)
        self.assertDictEqual(
            log.serialized_data["fields"],
            {
                "serialize_this": serialize_this.id,
                "subheading": "use a primary key for this serialization, please.",
                "value": 10,
            },
        )

    def test_serialize_related_with_kwargs(self):
        with freezegun.freeze_time(self.test_date):
            serialize_this = SerializeThisModel.objects.create(
                label="test label",
                nested={"foo": "bar"},
                timestamp=self.test_date,
            )
            instance = SerializeNaturalKeyRelatedModel.objects.create(
                serialize_this=serialize_this,
                subheading="use a natural key for this serialization, please.",
                value=11,
            )

        log = instance.history.first()
        self.assertTrue(isinstance(log, LogEntry))
        self.assertEqual(log.action, 0)
        self.assertDictEqual(
            log.serialized_data["fields"],
            {
                "serialize_this": "test label",
                "subheading": "use a natural key for this serialization, please.",
                "value": 11,
            },
        )

    def test_f_expressions(self):
        serialize_this = SerializeThisModel.objects.create(
            label="test label",
            nested={"foo": "bar"},
            timestamp=self.test_date,
            nullable=1,
        )
        serialize_this.nullable = models.F("nullable") + 1
        serialize_this.save()

        log = serialize_this.history.first()
        self.assertTrue(isinstance(log, LogEntry))
        self.assertEqual(log.action, 1)
        self.assertEqual(
            log.serialized_data["fields"]["nullable"],
            "F(nullable) + Value(1)",
        )


class TestAccessLog(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username="test_user", is_active=True)
        self.obj = SimpleModel.objects.create(text="For admin logentry test")

    def test_access_log(self):
        self.client.force_login(self.user)
        content_type = ContentType.objects.get_for_model(self.obj.__class__)

        # Check for log entries
        qs = LogEntry.objects.filter(content_type=content_type, object_pk=self.obj.pk)
        old_count = qs.count()

        self.client.get(reverse("simplemodel-detail", args=[self.obj.pk]))
        new_count = qs.count()
        self.assertEqual(new_count, old_count + 1)

        log_entry = qs.latest()
        self.assertEqual(int(log_entry.object_pk), self.obj.pk)
        self.assertEqual(log_entry.actor, self.user)
        self.assertEqual(log_entry.content_type, content_type)
        self.assertEqual(
            log_entry.action, LogEntry.Action.ACCESS, msg="Action is 'ACCESS'"
        )
        self.assertIsNone(log_entry.changes)
        self.assertEqual(log_entry.changes_dict, {})


class SignalTests(TestCase):
    def setUp(self):
        self.obj = SimpleModel.objects.create(text="I am not difficult.")
        self.my_pre_log_data = {
            "is_called": False,
            "my_sender": None,
            "my_instance": None,
            "my_action": None,
        }
        self.my_post_log_data = {
            "is_called": False,
            "my_sender": None,
            "my_instance": None,
            "my_action": None,
            "my_error": None,
            "my_log_entry": None,
        }

    def assertSignals(self, action):
        self.assertTrue(
            self.my_pre_log_data["is_called"], "pre_log hook receiver not called"
        )
        self.assertIs(self.my_pre_log_data["my_sender"], self.obj.__class__)
        self.assertIs(self.my_pre_log_data["my_instance"], self.obj)
        self.assertEqual(self.my_pre_log_data["my_action"], action)

        self.assertTrue(
            self.my_post_log_data["is_called"], "post_log hook receiver not called"
        )
        self.assertIs(self.my_post_log_data["my_sender"], self.obj.__class__)
        self.assertIs(self.my_post_log_data["my_instance"], self.obj)
        self.assertEqual(self.my_post_log_data["my_action"], action)
        self.assertIsNone(self.my_post_log_data["my_error"])
        self.assertIsNotNone(self.my_post_log_data["my_log_entry"])

    def test_custom_signals(self):
        my_ret_val = random.randint(0, 10000)
        my_other_ret_val = random.randint(0, 10000)

        def pre_log_receiver(sender, instance, action, **_kwargs):
            self.my_pre_log_data["is_called"] = True
            self.my_pre_log_data["my_sender"] = sender
            self.my_pre_log_data["my_instance"] = instance
            self.my_pre_log_data["my_action"] = action
            return my_ret_val

        def pre_log_receiver_extra(*_args, **_kwargs):
            return my_other_ret_val

        def post_log_receiver(
            sender, instance, action, error, log_entry, pre_log_results, **_kwargs
        ):
            self.my_post_log_data["is_called"] = True
            self.my_post_log_data["my_sender"] = sender
            self.my_post_log_data["my_instance"] = instance
            self.my_post_log_data["my_action"] = action
            self.my_post_log_data["my_error"] = error
            self.my_post_log_data["my_log_entry"] = log_entry

            self.assertEqual(len(pre_log_results), 2)

            found_first_result = False
            found_second_result = False
            for pre_log_fn, pre_log_result in pre_log_results:
                if pre_log_fn is pre_log_receiver and pre_log_result == my_ret_val:
                    found_first_result = True
            for pre_log_fn, pre_log_result in pre_log_results:
                if (
                    pre_log_fn is pre_log_receiver_extra
                    and pre_log_result == my_other_ret_val
                ):
                    found_second_result = True

            self.assertTrue(found_first_result)
            self.assertTrue(found_second_result)

            return my_ret_val

        pre_log.connect(pre_log_receiver)
        pre_log.connect(pre_log_receiver_extra)
        post_log.connect(post_log_receiver)

        self.obj = SimpleModel.objects.create(text="I am not difficult.")

        self.assertSignals(LogEntry.Action.CREATE)

    def test_disabled_logging(self):
        log_count = LogEntry.objects.count()

        def pre_log_receiver(sender, instance, action, **_kwargs):
            return True

        def pre_log_receiver_extra(*_args, **_kwargs):
            pass

        def pre_log_receiver_disable(*_args, **_kwargs):
            return False

        pre_log.connect(pre_log_receiver)
        pre_log.connect(pre_log_receiver_extra)

        self.obj = SimpleModel.objects.create(text="I am not difficult.")

        self.assertEqual(LogEntry.objects.count(), log_count + 1)

        log_count = LogEntry.objects.count()

        pre_log.connect(pre_log_receiver_disable)

        self.obj = SimpleModel.objects.create(text="I am not difficult.")

        self.assertEqual(LogEntry.objects.count(), log_count)

    def test_custom_signals_update(self):
        def pre_log_receiver(sender, instance, action, **_kwargs):
            self.my_pre_log_data["is_called"] = True
            self.my_pre_log_data["my_sender"] = sender
            self.my_pre_log_data["my_instance"] = instance
            self.my_pre_log_data["my_action"] = action

        def post_log_receiver(sender, instance, action, error, log_entry, **_kwargs):
            self.my_post_log_data["is_called"] = True
            self.my_post_log_data["my_sender"] = sender
            self.my_post_log_data["my_instance"] = instance
            self.my_post_log_data["my_action"] = action
            self.my_post_log_data["my_error"] = error
            self.my_post_log_data["my_log_entry"] = log_entry

        pre_log.connect(pre_log_receiver)
        post_log.connect(post_log_receiver)

        self.obj.text = "Changed Text"
        self.obj.save()

        self.assertSignals(LogEntry.Action.UPDATE)

    def test_custom_signals_delete(self):
        def pre_log_receiver(sender, instance, action, **_kwargs):
            self.my_pre_log_data["is_called"] = True
            self.my_pre_log_data["my_sender"] = sender
            self.my_pre_log_data["my_instance"] = instance
            self.my_pre_log_data["my_action"] = action

        def post_log_receiver(sender, instance, action, error, log_entry, **_kwargs):
            self.my_post_log_data["is_called"] = True
            self.my_post_log_data["my_sender"] = sender
            self.my_post_log_data["my_instance"] = instance
            self.my_post_log_data["my_action"] = action
            self.my_post_log_data["my_error"] = error
            self.my_post_log_data["my_log_entry"] = log_entry

        pre_log.connect(pre_log_receiver)
        post_log.connect(post_log_receiver)

        self.obj.delete()

        self.assertSignals(LogEntry.Action.DELETE)

    @patch("auditlog.receivers.LogEntry.objects")
    def test_signals_errors(self, log_entry_objects_mock):
        class CustomSignalError(BaseException):
            pass

        def post_log_receiver(error, **_kwargs):
            self.my_post_log_data["my_error"] = error

        post_log.connect(post_log_receiver)

        # create
        error_create = CustomSignalError(LogEntry.Action.CREATE)
        log_entry_objects_mock.log_create.side_effect = error_create
        with self.assertRaises(CustomSignalError):
            SimpleModel.objects.create(text="I am not difficult.")
        self.assertEqual(self.my_post_log_data["my_error"], error_create)

        # update
        error_update = CustomSignalError(LogEntry.Action.UPDATE)
        log_entry_objects_mock.log_create.side_effect = error_update
        with self.assertRaises(CustomSignalError):
            obj = SimpleModel.objects.get(pk=self.obj.pk)
            obj.text = "updating"
            obj.save()
        self.assertEqual(self.my_post_log_data["my_error"], error_update)

        # delete
        error_delete = CustomSignalError(LogEntry.Action.DELETE)
        log_entry_objects_mock.log_create.side_effect = error_delete
        with self.assertRaises(CustomSignalError):
            obj = SimpleModel.objects.get(pk=self.obj.pk)
            obj.delete()
        self.assertEqual(self.my_post_log_data["my_error"], error_delete)


@override_settings(AUDITLOG_DISABLE_ON_RAW_SAVE=True)
class DisableTest(TestCase):
    """
    All the other tests check logging, so this only needs to test disabled logging.
    """

    def test_create(self):
        # Mimic the way imports create objects
        inst = SimpleModel(
            text="I am a bit more difficult.",
            boolean=False,
            datetime=django_timezone.now(),
        )
        SimpleModel.save_base(inst, raw=True)
        self.assertEqual(0, LogEntry.objects.get_for_object(inst).count())

    def test_create_with_context_manager(self):
        with disable_auditlog():
            inst = SimpleModel.objects.create(text="I am a bit more difficult.")
        self.assertEqual(0, LogEntry.objects.get_for_object(inst).count())

    def test_update(self):
        inst = SimpleModel(
            text="I am a bit more difficult.",
            boolean=False,
            datetime=django_timezone.now(),
        )
        SimpleModel.save_base(inst, raw=True)
        inst.text = "I feel refreshed"
        inst.save_base(raw=True)
        self.assertEqual(0, LogEntry.objects.get_for_object(inst).count())

    def test_update_with_context_manager(self):
        inst = SimpleModel(
            text="I am a bit more difficult.",
            boolean=False,
            datetime=django_timezone.now(),
        )
        SimpleModel.save_base(inst, raw=True)
        with disable_auditlog():
            inst.text = "I feel refreshed"
            inst.save()
        self.assertEqual(0, LogEntry.objects.get_for_object(inst).count())

    def test_m2m(self):
        """
        Create m2m from fixture and check that nothing was logged.
        This only works with context manager
        """
        with disable_auditlog():
            management.call_command(
                "loaddata", "test_app/fixtures/m2m_test_fixture.json", verbosity=0
            )
        recursive = ManyRelatedModel.objects.get(pk=1)
        self.assertEqual(0, LogEntry.objects.get_for_object(recursive).count())
        related = ManyRelatedOtherModel.objects.get(pk=1)
        self.assertEqual(0, LogEntry.objects.get_for_object(related).count())


class MissingModelTest(TestCase):
    def setUp(self):
        # Create a log entry, then unregister the model
        self.obj = SimpleModel.objects.create(text="I am old.")
        auditlog.unregister(SimpleModel)

    def tearDown(self):
        # Re-register the model for other tests
        auditlog.register(SimpleModel)

    def test_get_changes_for_missing_model(self):
        history = self.obj.history.latest()
        self.assertEqual(history.changes_dict["text"][1], self.obj.text)
        self.assertEqual(history.changes_display_dict["text"][1], self.obj.text)


class ModelManagerTest(TestCase):
    """
    This does not directly assert the configured manager, but its behaviour.
    The "secret" object should not be accessible, as the queryset is overridden.
    """

    def setUp(self):
        self.secret = SwappedManagerModel.objects.create(is_secret=True, name="Secret")
        self.public = SwappedManagerModel.objects.create(is_secret=False, name="Public")

    def test_update_secret(self):
        self.secret.name = "Updated"
        self.secret.save()
        log = LogEntry.objects.get_for_object(self.secret).first()
        self.assertEqual(log.action, LogEntry.Action.UPDATE)
        self.assertEqual(log.changes_dict["name"], ["None", "Updated"])

    def test_update_public(self):
        self.public.name = "Updated"
        self.public.save()
        log = LogEntry.objects.get_for_object(self.public).first()
        self.assertEqual(log.action, LogEntry.Action.UPDATE)
        self.assertEqual(log.changes_dict["name"], ["Public", "Updated"])


class TestMaskStr(TestCase):
    """Test the mask_str function that masks sensitive data."""

    def test_mask_str_empty(self):
        self.assertEqual(mask_str(""), "")

    def test_mask_str_single_char(self):
        self.assertEqual(mask_str("a"), "a")

    def test_mask_str_even_length(self):
        self.assertEqual(mask_str("1234"), "**34")

    def test_mask_str_odd_length(self):
        self.assertEqual(mask_str("12345"), "**345")

    def test_mask_str_long_text(self):
        self.assertEqual(mask_str("confidential"), "******ential")


class CustomMaskModelTest(TestCase):
    def test_custom_mask_function(self):
        instance = CustomMaskModel.objects.create(
            credit_card="1234567890123456", text="Some text"
        )
        self.assertEqual(
            instance.history.latest().changes_dict["credit_card"][1],
            "****3456",
            msg="The custom masking function should mask all but last 4 digits",
        )

    def test_custom_mask_function_short_value(self):
        """Test that custom masking function handles short values correctly"""
        instance = CustomMaskModel.objects.create(credit_card="123", text="Some text")
        self.assertEqual(
            instance.history.latest().changes_dict["credit_card"][1],
            "123",
            msg="The custom masking function should not mask values shorter than 4 characters",
        )

    def test_custom_mask_function_serialized_data(self):
        instance = CustomMaskModel.objects.create(
            credit_card="1234567890123456", text="Some text"
        )
        log = instance.history.latest()
        self.assertTrue(isinstance(log, LogEntry))
        self.assertEqual(log.action, LogEntry.Action.CREATE)

        # Update to trigger serialization
        instance.credit_card = "9876543210987654"
        instance.save()

        log = instance.history.latest()
        self.assertEqual(
            log.changes_dict["credit_card"][1],
            "****7654",
            msg="The custom masking function should be used in serialized data",
        )