diff --git a/tests/test_pi_models.py b/tests/test_pi_models.py new file mode 100644 index 0000000..ddbf457 --- /dev/null +++ b/tests/test_pi_models.py @@ -0,0 +1,47 @@ +"""Test the pi models.""" +from unittest import mock + +from django.test import TestCase +from django.utils.timezone import now + +from pi.models import PiLog + + +class PiLogTest(TestCase): + """Test pi models.""" + + def test_hit_calculation(self): + """Test that x,y combinations are properly considered inside or outside the circle.""" + hit_item = PiLog(simulation_x=0.0, simulation_y=0.0, total_count=0, total_count_inside=0) + miss_item = PiLog(simulation_x=1.0, simulation_y=1.0, total_count=0, total_count_inside=0) + + self.assertTrue(hit_item.hit) + self.assertFalse(miss_item.hit) + + def test_value_calculation(self): + """Test that a simulation's value of pi can be calculated.""" + item = PiLog(simulation_x=0.0, simulation_y=0.0, total_count=1000, total_count_inside=788) + zero_item = PiLog(simulation_x=0.0, simulation_y=0.0, total_count=0, total_count_inside=0) + + self.assertEqual(item.value, 3.152) + self.assertEqual(zero_item.value, 0.0) + + def test_string_repr(self): + """Test the string repr of a simulation log entry.""" + item = PiLog(simulation_x=0.0, simulation_y=0.0, total_count=1000, total_count_inside=788, + created=now()) + + self.assertIn("(788/1000) @ ", str(item)) + + def test_simulation_inside_determination(self): + """Test that running a simulation passes the proper inside value.""" + # get at least one simulation in the DB + original_item, _, _ = PiLog.objects.simulate() + + with mock.patch('random.random', return_value=1.0): + miss_item, _, _ = PiLog.objects.simulate() + self.assertEqual(miss_item.total_count_inside, original_item.total_count_inside) + + with mock.patch('random.random', return_value=0.0): + hit_item, _, _ = PiLog.objects.simulate() + self.assertGreater(hit_item.total_count_inside, original_item.total_count_inside) diff --git a/tests/test_pi_views.py b/tests/test_pi_views.py new file mode 100644 index 0000000..0403f73 --- /dev/null +++ b/tests/test_pi_views.py @@ -0,0 +1,25 @@ +"""Test the pi package's views.""" +from django.contrib.auth.models import User +from rest_framework.status import HTTP_201_CREATED +from rest_framework.test import APITestCase + +from pi.models import PiLog + + +class PiAPITest(APITestCase): + """Test pi DRF views.""" + + def setUp(self): + """Do pre-test stuff.""" + self.client = self.client_class() + self.user = User.objects.create(username='test') + self.client.force_authenticate(user=self.user) + + def test_simulate_creates_simulation(self): + """Test that the simulate action creates a log entry.""" + self.assertEqual(PiLog.objects.count(), 0) + + resp = self.client.post('/pi/api/simulations/simulate/') + + self.assertEqual(resp.status_code, HTTP_201_CREATED) + self.assertEqual(PiLog.objects.count(), 2) # 2 because 0 entry and the real entry