wow, unit tests! pi is covered (except for the irc plugin)

I think I'm going to move the irc stuff into a separate project in the
future so I'm not worried about testing that one yet
This commit is contained in:
Brian S. Stephan 2020-10-25 11:16:48 -05:00
parent d5e5343193
commit a0a1aa10f4
2 changed files with 72 additions and 0 deletions

47
tests/test_pi_models.py Normal file
View File

@ -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)

25
tests/test_pi_views.py Normal file
View File

@ -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