Skip to content

Instantly share code, notes, and snippets.

@jpwhite3
Last active September 21, 2023 13:58
Show Gist options
  • Save jpwhite3/9bbdf19f1f17d1c890295211143a3657 to your computer and use it in GitHub Desktop.
Save jpwhite3/9bbdf19f1f17d1c890295211143a3657 to your computer and use it in GitHub Desktop.
import unittest
import random
from typing import List
class D20:
minimum_value: int = 1
maximum_value: int = 20
number_range: List[int] = range(minimum_value, maximum_value + 1)
def __init__(self) -> None:
self.value = None
def roll(self):
self.value = random.choice(self.number_range)
class TestD20(unittest.TestCase):
def test_initialization(self):
testobj = D20()
expected_minimum_value = 1
expected_maximum_value = 20
self.assertEqual(expected_minimum_value, testobj.minimum_value)
self.assertEqual(expected_maximum_value, testobj.maximum_value)
self.assertIsNone(testobj.value)
def test_value_changes_from_default_value(self):
testobj = D20()
testobj.roll()
actual_value = testobj.value
self.assertIsNotNone(actual_value)
def test_roll_returns_number_within_bounds(self):
testobj = D20()
testobj.roll()
actual_roll = testobj.value
self.assertIn(actual_roll, testobj.number_range)
def test_roll_is_not_static(self):
testobj = D20()
roll_values = []
for i in range(20):
testobj.roll()
roll_values.append(testobj.value)
unique_roll_values = list(set(roll_values))
self.assertGreater(len(unique_roll_values), 1)
def test_roll_hits_every_number(self):
testobj = D20()
roll_values = []
for i in range(100):
testobj.roll()
roll_values.append(testobj.value)
unique_roll_values = list(set(roll_values))
for i in range(1, 21):
self.assertIn(i, unique_roll_values)
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment