Coverage for apis_core/history/tests/test_simple_history.py: 100%

45 statements  

« prev     ^ index     » next       coverage.py v7.5.3, created at 2025-06-25 10:00 +0000

1from datetime import datetime, timedelta 

2 

3from django.test import TestCase 

4 

5from sample_project.models import Person, Place, Profession 

6 

7 

8class SimpleHistoryTestCase(TestCase): 

9 """Test of the simple_history package using the demo project""" 

10 

11 def setUp(self): 

12 self.Person = Person 

13 self.Place = Place 

14 self.Profession = Profession 

15 

16 Person.objects.create(forename="John", surname="Doe") 

17 Place.objects.create( 

18 label="Steyr", _history_date=datetime.now() - timedelta(hours=0, minutes=50) 

19 ) 

20 

21 def test_history(self): 

22 """Tests the simple version of attributes changed on a models instance.""" 

23 pers = self.Person.objects.get(forename="John") 

24 pers.forename = "Jane" 

25 pers.save() 

26 self.assertEqual(pers.forename, "Jane") 

27 pers_history = pers.history.all() 

28 assert len(pers_history) == 2 

29 self.assertEqual("Jane", pers.history.most_recent().forename) 

30 self.assertEqual("John", pers.history.earliest().forename) 

31 

32 def test_history_delete_entry(self): 

33 """Tests the deletion of an entry.""" 

34 pers = self.Person.objects.get(forename="John") 

35 pers.delete() 

36 assert len(self.Person.history.all()) == 2 

37 

38 def test_history_merge(self): 

39 """Tests the merge function of the Place model. This is still expected to fail.""" 

40 pl1 = self.Place.objects.first() 

41 pl2 = self.Place.objects.create( 

42 label="Test", _history_date=datetime.now() - timedelta(hours=0, minutes=10) 

43 ) 

44 pl1.merge_with([pl2]) 

45 print("save()") 

46 

47 def test_m2m_save(self): 

48 """Test if m2m profession is saved correctly.""" 

49 pers = self.Person.objects.create( 

50 forename="John", 

51 _history_date=datetime.now() - timedelta(hours=0, minutes=10), 

52 ) 

53 self.assertEqual(pers.forename, "John") 

54 pers_history = pers.history.all() 

55 assert len(pers_history) == 1 

56 prof = self.Profession.objects.create(name="Test") 

57 pers.profession.add(prof) 

58 pers.forename = "Jane" 

59 pers.save() 

60 assert len(pers.profession.all()) == 1 

61 assert len(pers.history.latest().profession.all()) == 1 

62 assert len(pers.history.earliest().profession.all()) == 0 

63 

64 def test_history_date(self): 

65 """Test that history is set correctly when not manually set.""" 

66 pers = self.Person.objects.all().first() 

67 pers.forename = "Jane" 

68 pers.save() 

69 assert pers.history.earliest().history_date < pers.history.latest().history_date