thermostat-alt.py (1915B)
1 import unittest 2 from datetime import datetime 3 4 class Thermostat: 5 6 def __init__(self): 7 self.setPoints = [] 8 9 def GetCurrentRequiredTemperature(self): 10 time = int(datetime.now().strftime("%H")) 11 return self.GetCurrentRequiredTemperatureAtTime(time) 12 13 def GetCurrentRequiredTemperatureAtTime(self, time): 14 passedSetPoints = [sp for sp in self.setPoints if sp[0] <= time] 15 lastPassedSetPoint = max(passedSetPoints, default = (0, 10), key = lambda sp: sp[0]) 16 return lastPassedSetPoint[1] 17 18 def AddSetPoint(self, hour, temperature): 19 self.setPoints.append((hour, temperature)) 20 21 class ThermostatTests(unittest.TestCase): 22 23 def test_GivenNewThermostat_ThenRequiredTemperatureIs10(self): 24 thermostat = Thermostat() 25 currentRequiredTemperature = thermostat.GetCurrentRequiredTemperature() 26 self.assertEqual(currentRequiredTemperature, 10) 27 28 def test_GivenIAddedASetPoint_WhenTimeIsAfterSetPoint_ThenRequiredTemperatureIsChanged(self): 29 hour = 10 30 requiredTemperature = 30 31 thermostat = Thermostat() 32 thermostat.AddSetPoint(hour, requiredTemperature) 33 self.assertEqual(thermostat.GetCurrentRequiredTemperatureAtTime(hour), requiredTemperature) 34 35 def test_GivenIAddedSetPoint_WhenTimeIsBeforeSetPoint_ThenRequiredTemperatureNotChanged(self): 36 hour = 7 37 requiredTemperature = 25 38 thermostat = Thermostat() 39 oldRequiredTemperature = thermostat.GetCurrentRequiredTemperatureAtTime(hour-1) 40 thermostat.AddSetPoint(hour, requiredTemperature) 41 newRequiredTemperature = thermostat.GetCurrentRequiredTemperatureAtTime(hour-1) 42 self.assertEqual(oldRequiredTemperature, newRequiredTemperature) 43 44 def test_GivenTwoSetPoints_WhenTimeIsBetweenThem_ThenRequiredTemperatureIsFirst(self): 45 hour1, hour2 = 12, 15 46 temp1, temp2 = 55, 75 47 thermostat = Thermostat() 48 thermostat.AddSetPoint(hour1, temp1) 49 thermostat.AddSetPoint(hour2, temp2) 50 self.assertEqual(thermostat.GetCurrentRequiredTemperatureAtTime(14), 55)