thermostat

Just a TDD exercise
git clone https://git.tronto.net/thermostat
Download | Log | Files | Refs | README

thermostat.py (2012B)


      1 import unittest
      2 from datetime import datetime
      3 
      4 class Thermostat:
      5 
      6 	def __init__(self):
      7 		self.setPoints = []
      8 
      9 	def GetCurrentTime(self):
     10 		return int(datetime.now().strftime("%H"))
     11 
     12 	def GetCurrentRequiredTemperature(self):
     13 		time = self.GetCurrentTime()
     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 TestableThermostat(Thermostat):
     22 
     23 	def __init__(self, hour):
     24 		self.hour = hour
     25 		self.setPoints = []
     26 
     27 	def GetCurrentTime(self):
     28 		return self.hour
     29 
     30 class ThermostatTests(unittest.TestCase):
     31 
     32 	def test_GivenNewThermostat_ThenRequiredTemperatureIs10(self):
     33 		thermostat = Thermostat()
     34 		currentRequiredTemperature = thermostat.GetCurrentRequiredTemperature()
     35 		self.assertEqual(currentRequiredTemperature, 10)
     36 
     37 	def test_GivenIAddedASetPoint_WhenTimeIsAfterSetPoint_ThenRequiredTemperatureIsChanged(self):
     38 		hour = 10
     39 		requiredTemperature = 30
     40 		thermostat = TestableThermostat(hour)
     41 		thermostat.AddSetPoint(hour, requiredTemperature)
     42 		self.assertEqual(thermostat.GetCurrentRequiredTemperature(), requiredTemperature)
     43 
     44 	def test_GivenIAddedSetPoint_WhenTimeIsBeforeSetPoint_ThenRequiredTemperatureNotChanged(self):
     45 		hour = 7
     46 		requiredTemperature = 25
     47 		thermostat = TestableThermostat(hour-1)
     48 		oldRequiredTemperature = thermostat.GetCurrentRequiredTemperature()
     49 		thermostat.AddSetPoint(hour, requiredTemperature)
     50 		newRequiredTemperature = thermostat.GetCurrentRequiredTemperature()
     51 		self.assertEqual(oldRequiredTemperature, newRequiredTemperature)
     52 
     53 	def test_GivenTwoSetPoints_WhenTimeIsBetweenThem_ThenRequiredTemperatureIsFirst(self):
     54 		hour1, hour2 = 12, 15
     55 		temp1, temp2 = 55, 75
     56 		thermostat = TestableThermostat(14)
     57 		thermostat.AddSetPoint(hour1, temp1)
     58 		thermostat.AddSetPoint(hour2, temp2)
     59 		self.assertEqual(thermostat.GetCurrentRequiredTemperature(), 55)