diff --git a/homeassistant/auth/mfa_modules/__init__.py b/homeassistant/auth/mfa_modules/__init__.py index 1746ef38f..331306367 100644 --- a/homeassistant/auth/mfa_modules/__init__.py +++ b/homeassistant/auth/mfa_modules/__init__.py @@ -104,7 +104,7 @@ class SetupFlow(data_entry_flow.FlowHandler): -> Dict[str, Any]: """Handle the first step of setup flow. - Return self.async_show_form(step_id='init') if user_input == None. + Return self.async_show_form(step_id='init') if user_input is None. Return self.async_create_entry(data={'result': result}) if finish. """ errors = {} # type: Dict[str, str] diff --git a/homeassistant/auth/mfa_modules/totp.py b/homeassistant/auth/mfa_modules/totp.py index 9b5896ef6..68f4e1d05 100644 --- a/homeassistant/auth/mfa_modules/totp.py +++ b/homeassistant/auth/mfa_modules/totp.py @@ -176,7 +176,7 @@ class TotpSetupFlow(SetupFlow): -> Dict[str, Any]: """Handle the first step of setup flow. - Return self.async_show_form(step_id='init') if user_input == None. + Return self.async_show_form(step_id='init') if user_input is None. Return self.async_create_entry(data={'result': result}) if finish. """ import pyotp diff --git a/homeassistant/auth/providers/__init__.py b/homeassistant/auth/providers/__init__.py index e96f6d7eb..9ca4232b6 100644 --- a/homeassistant/auth/providers/__init__.py +++ b/homeassistant/auth/providers/__init__.py @@ -179,7 +179,7 @@ class LoginFlow(data_entry_flow.FlowHandler): -> Dict[str, Any]: """Handle the first step of login flow. - Return self.async_show_form(step_id='init') if user_input == None. + Return self.async_show_form(step_id='init') if user_input is None. Return await self.async_finish(flow_result) if login init step pass. """ raise NotImplementedError diff --git a/tests/components/alarm_control_panel/test_manual.py b/tests/components/alarm_control_panel/test_manual.py index 02085a44b..7d87d05b5 100644 --- a/tests/components/alarm_control_panel/test_manual.py +++ b/tests/components/alarm_control_panel/test_manual.py @@ -35,11 +35,11 @@ class TestAlarmControlPanelManual(unittest.TestCase): mock = MagicMock() add_entities = mock.MagicMock() demo.setup_platform(self.hass, {}, add_entities) - self.assertEqual(add_entities.call_count, 1) + assert add_entities.call_count == 1 def test_arm_home_no_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -47,22 +47,22 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 0, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_home(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_HOME, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_HOME == \ + self.hass.states.get(entity_id).state def test_arm_home_with_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -70,18 +70,18 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 1, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_home(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state state = self.hass.states.get(entity_id) assert state.attributes['post_pending_state'] == STATE_ALARM_ARMED_HOME @@ -97,7 +97,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): def test_arm_home_with_invalid_code(self): """Attempt to arm home without a valid code.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -105,22 +105,22 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 1, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_home(self.hass, CODE + '2') self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_arm_away_no_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -128,22 +128,22 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 0, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state def test_arm_home_with_template_code(self): """Attempt to arm with a template-based code.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -151,25 +151,25 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code_template': '{{ "abc" }}', 'pending_time': 0, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' self.hass.start() self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_home(self.hass, 'abc') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_ARMED_HOME, state.state) + assert STATE_ALARM_ARMED_HOME == state.state def test_arm_away_with_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -177,18 +177,18 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 1, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state state = self.hass.states.get(entity_id) assert state.attributes['post_pending_state'] == STATE_ALARM_ARMED_AWAY @@ -204,7 +204,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): def test_arm_away_with_invalid_code(self): """Attempt to arm away without a valid code.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -212,22 +212,22 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 1, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE + '2') self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_arm_night_no_pending(self): """Test arm night method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -235,22 +235,22 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 0, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_night(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_NIGHT, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_NIGHT == \ + self.hass.states.get(entity_id).state def test_arm_night_with_pending(self): """Test arm night method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -258,18 +258,18 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 1, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_night(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state state = self.hass.states.get(entity_id) assert state.attributes['post_pending_state'] == \ @@ -288,12 +288,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): common.alarm_arm_night(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_NIGHT, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_NIGHT == \ + self.hass.states.get(entity_id).state def test_arm_night_with_invalid_code(self): """Attempt to night home without a valid code.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -301,40 +301,40 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 1, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_night(self.hass, CODE + '2') self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_no_pending(self): """Test triggering when no pending submitted method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'trigger_time': 1, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=60) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -342,12 +342,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state def test_trigger_with_delay(self): """Test trigger method and switch from pending to triggered.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -356,26 +356,26 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'delay_time': 1, 'pending_time': 0, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_TRIGGERED, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_TRIGGERED == \ + state.attributes['post_pending_state'] future = dt_util.utcnow() + timedelta(seconds=1) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -384,11 +384,11 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_TRIGGERED, state.state) + assert STATE_ALARM_TRIGGERED == state.state def test_trigger_zero_trigger_time(self): """Test disabled trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -396,22 +396,22 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'pending_time': 0, 'trigger_time': 0, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_zero_trigger_time_with_pending(self): """Test disabled trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -419,22 +419,22 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'pending_time': 2, 'trigger_time': 0, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_with_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -442,18 +442,18 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'pending_time': 2, 'trigger_time': 3, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state state = self.hass.states.get(entity_id) assert state.attributes['post_pending_state'] == STATE_ALARM_TRIGGERED @@ -478,7 +478,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): def test_trigger_with_unused_specific_delay(self): """Test trigger method and switch from pending to triggered.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -490,26 +490,26 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'delay_time': 10 }, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_TRIGGERED, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_TRIGGERED == \ + state.attributes['post_pending_state'] future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -522,7 +522,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): def test_trigger_with_specific_delay(self): """Test trigger method and switch from pending to triggered.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -534,26 +534,26 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'delay_time': 1 }, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_TRIGGERED, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_TRIGGERED == \ + state.attributes['post_pending_state'] future = dt_util.utcnow() + timedelta(seconds=1) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -566,7 +566,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): def test_trigger_with_pending_and_delay(self): """Test trigger method and switch from pending to triggered.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -578,18 +578,18 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'pending_time': 1 }, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() @@ -619,7 +619,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): def test_trigger_with_pending_and_specific_delay(self): """Test trigger method and switch from pending to triggered.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -634,18 +634,18 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'pending_time': 1 }, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() @@ -675,7 +675,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): def test_armed_home_with_specific_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -684,15 +684,15 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'armed_home': { 'pending_time': 2 } - }})) + }}) entity_id = 'alarm_control_panel.test' common.alarm_arm_home(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=2) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -700,12 +700,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_HOME, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_HOME == \ + self.hass.states.get(entity_id).state def test_armed_away_with_specific_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -714,15 +714,15 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'armed_away': { 'pending_time': 2 } - }})) + }}) entity_id = 'alarm_control_panel.test' common.alarm_arm_away(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=2) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -730,12 +730,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state def test_armed_night_with_specific_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -744,15 +744,15 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'armed_night': { 'pending_time': 2 } - }})) + }}) entity_id = 'alarm_control_panel.test' common.alarm_arm_night(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=2) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -760,12 +760,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_NIGHT, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_NIGHT == \ + self.hass.states.get(entity_id).state def test_trigger_with_specific_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -776,15 +776,15 @@ class TestAlarmControlPanelManual(unittest.TestCase): }, 'trigger_time': 3, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=2) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -792,8 +792,8 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -801,12 +801,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_with_disarm_after_trigger(self): """Test disarm after trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -814,18 +814,18 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'trigger_time': 5, 'pending_time': 0, 'disarm_after_trigger': True - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -833,12 +833,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_with_zero_specific_trigger_time(self): """Test trigger method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -849,22 +849,22 @@ class TestAlarmControlPanelManual(unittest.TestCase): }, 'pending_time': 0, 'disarm_after_trigger': True - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_with_unused_zero_specific_trigger_time(self): """Test disarm after trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -875,18 +875,18 @@ class TestAlarmControlPanelManual(unittest.TestCase): }, 'pending_time': 0, 'disarm_after_trigger': True - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -894,12 +894,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_with_specific_trigger_time(self): """Test disarm after trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -909,18 +909,18 @@ class TestAlarmControlPanelManual(unittest.TestCase): }, 'pending_time': 0, 'disarm_after_trigger': True - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -928,12 +928,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_with_no_disarm_after_trigger(self): """Test disarm after trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -941,24 +941,24 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'trigger_time': 5, 'pending_time': 0, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -966,12 +966,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state def test_back_to_back_trigger_with_no_disarm_after_trigger(self): """Test disarm after trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -979,24 +979,24 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'trigger_time': 5, 'pending_time': 0, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -1004,14 +1004,14 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -1019,36 +1019,36 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state def test_disarm_while_pending_trigger(self): """Test disarming while pending state.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', 'name': 'test', 'trigger_time': 5, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state common.alarm_disarm(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -1056,12 +1056,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_disarm_during_trigger_with_invalid_code(self): """Test disarming while code is invalid.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -1069,24 +1069,24 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'pending_time': 5, 'code': CODE + '2', 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state common.alarm_disarm(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -1094,12 +1094,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state def test_disarm_with_template_code(self): """Attempt to disarm with a valid or invalid template-based code.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -1108,37 +1108,37 @@ class TestAlarmControlPanelManual(unittest.TestCase): '{{ "" if from_state == "disarmed" else "abc" }}', 'pending_time': 0, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' self.hass.start() self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_home(self.hass, 'def') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_ARMED_HOME, state.state) + assert STATE_ALARM_ARMED_HOME == state.state common.alarm_disarm(self.hass, 'def') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_ARMED_HOME, state.state) + assert STATE_ALARM_ARMED_HOME == state.state common.alarm_disarm(self.hass, 'abc') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_DISARMED, state.state) + assert STATE_ALARM_DISARMED == state.state def test_arm_custom_bypass_no_pending(self): """Test arm custom bypass method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -1146,22 +1146,22 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 0, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_custom_bypass(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_CUSTOM_BYPASS, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_CUSTOM_BYPASS == \ + self.hass.states.get(entity_id).state def test_arm_custom_bypass_with_pending(self): """Test arm custom bypass method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -1169,18 +1169,18 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 1, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_custom_bypass(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state state = self.hass.states.get(entity_id) assert state.attributes['post_pending_state'] == \ @@ -1197,7 +1197,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): def test_arm_custom_bypass_with_invalid_code(self): """Attempt to custom bypass without a valid code.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -1205,22 +1205,22 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'code': CODE, 'pending_time': 1, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_custom_bypass(self.hass, CODE + '2') self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_armed_custom_bypass_with_specific_pending(self): """Test arm custom bypass method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -1229,15 +1229,15 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'armed_custom_bypass': { 'pending_time': 2 } - }})) + }}) entity_id = 'alarm_control_panel.test' common.alarm_arm_custom_bypass(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=2) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -1245,12 +1245,12 @@ class TestAlarmControlPanelManual(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_CUSTOM_BYPASS, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_CUSTOM_BYPASS == \ + self.hass.states.get(entity_id).state def test_arm_away_after_disabled_disarmed(self): """Test pending state with and without zero trigger time.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', @@ -1265,32 +1265,32 @@ class TestAlarmControlPanelManual(unittest.TestCase): 'trigger_time': 0 }, 'disarm_after_trigger': False - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_DISARMED, - state.attributes['pre_pending_state']) - self.assertEqual(STATE_ALARM_ARMED_AWAY, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_DISARMED == \ + state.attributes['pre_pending_state'] + assert STATE_ALARM_ARMED_AWAY == \ + state.attributes['post_pending_state'] common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_DISARMED, - state.attributes['pre_pending_state']) - self.assertEqual(STATE_ALARM_ARMED_AWAY, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_DISARMED == \ + state.attributes['pre_pending_state'] + assert STATE_ALARM_ARMED_AWAY == \ + state.attributes['post_pending_state'] future = dt_util.utcnow() + timedelta(seconds=1) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -1299,17 +1299,17 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_ARMED_AWAY, state.state) + assert STATE_ALARM_ARMED_AWAY == state.state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_ARMED_AWAY, - state.attributes['pre_pending_state']) - self.assertEqual(STATE_ALARM_TRIGGERED, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_ARMED_AWAY == \ + state.attributes['pre_pending_state'] + assert STATE_ALARM_TRIGGERED == \ + state.attributes['post_pending_state'] future += timedelta(seconds=1) with patch(('homeassistant.components.alarm_control_panel.manual.' @@ -1318,4 +1318,4 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_TRIGGERED, state.state) + assert STATE_ALARM_TRIGGERED == state.state diff --git a/tests/components/alarm_control_panel/test_manual_mqtt.py b/tests/components/alarm_control_panel/test_manual_mqtt.py index 4e2ec6a94..3d063f8a3 100644 --- a/tests/components/alarm_control_panel/test_manual_mqtt.py +++ b/tests/components/alarm_control_panel/test_manual_mqtt.py @@ -54,7 +54,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): def test_arm_home_no_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -64,22 +64,22 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_home(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_HOME, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_HOME == \ + self.hass.states.get(entity_id).state def test_arm_home_with_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -89,18 +89,18 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_home(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state state = self.hass.states.get(entity_id) assert state.attributes['post_pending_state'] == STATE_ALARM_ARMED_HOME @@ -111,12 +111,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_HOME, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_HOME == \ + self.hass.states.get(entity_id).state def test_arm_home_with_invalid_code(self): """Attempt to arm home without a valid code.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -126,22 +126,22 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_home(self.hass, CODE + '2') self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_arm_away_no_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -151,22 +151,22 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state def test_arm_home_with_template_code(self): """Attempt to arm with a template-based code.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -176,25 +176,25 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' self.hass.start() self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_home(self.hass, 'abc') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_ARMED_HOME, state.state) + assert STATE_ALARM_ARMED_HOME == state.state def test_arm_away_with_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -204,18 +204,18 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state state = self.hass.states.get(entity_id) assert state.attributes['post_pending_state'] == STATE_ALARM_ARMED_AWAY @@ -226,12 +226,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state def test_arm_away_with_invalid_code(self): """Attempt to arm away without a valid code.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -241,22 +241,22 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE + '2') self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_arm_night_no_pending(self): """Test arm night method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -266,22 +266,22 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_night(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_NIGHT, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_NIGHT == \ + self.hass.states.get(entity_id).state def test_arm_night_with_pending(self): """Test arm night method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -291,18 +291,18 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_night(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state state = self.hass.states.get(entity_id) assert state.attributes['post_pending_state'] == \ @@ -314,19 +314,19 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_NIGHT, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_NIGHT == \ + self.hass.states.get(entity_id).state # Do not go to the pending state when updating to the same state common.alarm_arm_night(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_NIGHT, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_NIGHT == \ + self.hass.states.get(entity_id).state def test_arm_night_with_invalid_code(self): """Attempt to arm night without a valid code.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -336,22 +336,22 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_night(self.hass, CODE + '2') self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_no_pending(self): """Test triggering when no pending submitted method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -360,18 +360,18 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=60) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -379,12 +379,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state def test_trigger_with_delay(self): """Test trigger method and switch from pending to triggered.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -395,26 +395,26 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state' - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_TRIGGERED, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_TRIGGERED == \ + state.attributes['post_pending_state'] future = dt_util.utcnow() + timedelta(seconds=1) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -423,11 +423,11 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_TRIGGERED, state.state) + assert STATE_ALARM_TRIGGERED == state.state def test_trigger_zero_trigger_time(self): """Test disabled trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -437,22 +437,22 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state' - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_zero_trigger_time_with_pending(self): """Test disabled trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -462,22 +462,22 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state' - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_with_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -487,18 +487,18 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state state = self.hass.states.get(entity_id) assert state.attributes['post_pending_state'] == STATE_ALARM_TRIGGERED @@ -509,8 +509,8 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -518,12 +518,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_with_disarm_after_trigger(self): """Test disarm after trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -533,18 +533,18 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': True, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -552,12 +552,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_with_zero_specific_trigger_time(self): """Test trigger method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -570,22 +570,22 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': True, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state' - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_with_unused_zero_specific_trigger_time(self): """Test disarm after trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -598,18 +598,18 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': True, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state' - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -617,12 +617,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_trigger_with_specific_trigger_time(self): """Test disarm after trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -634,18 +634,18 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': True, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state' - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -653,12 +653,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_back_to_back_trigger_with_no_disarm_after_trigger(self): """Test no disarm after back to back trigger.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -668,24 +668,24 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE, entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -693,14 +693,14 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -708,12 +708,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state def test_disarm_while_pending_trigger(self): """Test disarming while pending state.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -722,24 +722,24 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state common.alarm_disarm(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -747,12 +747,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_disarm_during_trigger_with_invalid_code(self): """Test disarming while code is invalid.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -762,24 +762,24 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state common.alarm_disarm(self.hass, entity_id=entity_id) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -787,12 +787,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state def test_trigger_with_unused_specific_delay(self): """Test trigger method and switch from pending to triggered.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -806,26 +806,26 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state' - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_TRIGGERED, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_TRIGGERED == \ + state.attributes['post_pending_state'] future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -838,7 +838,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): def test_trigger_with_specific_delay(self): """Test trigger method and switch from pending to triggered.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -852,26 +852,26 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state' - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_TRIGGERED, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_TRIGGERED == \ + state.attributes['post_pending_state'] future = dt_util.utcnow() + timedelta(seconds=1) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -884,7 +884,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): def test_trigger_with_pending_and_delay(self): """Test trigger method and switch from pending to triggered.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -898,18 +898,18 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state' - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() @@ -939,7 +939,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): def test_trigger_with_pending_and_specific_delay(self): """Test trigger method and switch from pending to triggered.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -956,18 +956,18 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state' - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() @@ -997,7 +997,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): def test_armed_home_with_specific_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -1008,15 +1008,15 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): }, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' common.alarm_arm_home(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=2) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -1024,12 +1024,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_HOME, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_HOME == \ + self.hass.states.get(entity_id).state def test_armed_away_with_specific_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -1040,15 +1040,15 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): }, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' common.alarm_arm_away(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=2) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -1056,12 +1056,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state def test_armed_night_with_specific_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -1072,15 +1072,15 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): }, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' common.alarm_arm_night(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=2) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -1088,12 +1088,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_NIGHT, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_NIGHT == \ + self.hass.states.get(entity_id).state def test_trigger_with_specific_pending(self): """Test arm home method.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -1106,15 +1106,15 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=2) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -1122,8 +1122,8 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_TRIGGERED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_TRIGGERED == \ + self.hass.states.get(entity_id).state future = dt_util.utcnow() + timedelta(seconds=5) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -1131,12 +1131,12 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_arm_away_after_disabled_disarmed(self): """Test pending state with and without zero trigger time.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -1153,32 +1153,32 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_away(self.hass, CODE) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_DISARMED, - state.attributes['pre_pending_state']) - self.assertEqual(STATE_ALARM_ARMED_AWAY, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_DISARMED == \ + state.attributes['pre_pending_state'] + assert STATE_ALARM_ARMED_AWAY == \ + state.attributes['post_pending_state'] common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_DISARMED, - state.attributes['pre_pending_state']) - self.assertEqual(STATE_ALARM_ARMED_AWAY, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_DISARMED == \ + state.attributes['pre_pending_state'] + assert STATE_ALARM_ARMED_AWAY == \ + state.attributes['post_pending_state'] future = dt_util.utcnow() + timedelta(seconds=1) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -1187,17 +1187,17 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_ARMED_AWAY, state.state) + assert STATE_ALARM_ARMED_AWAY == state.state common.alarm_trigger(self.hass, entity_id=entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_PENDING, state.state) - self.assertEqual(STATE_ALARM_ARMED_AWAY, - state.attributes['pre_pending_state']) - self.assertEqual(STATE_ALARM_TRIGGERED, - state.attributes['post_pending_state']) + assert STATE_ALARM_PENDING == state.state + assert STATE_ALARM_ARMED_AWAY == \ + state.attributes['pre_pending_state'] + assert STATE_ALARM_TRIGGERED == \ + state.attributes['post_pending_state'] future += timedelta(seconds=1) with patch(('homeassistant.components.alarm_control_panel.manual_mqtt.' @@ -1206,11 +1206,11 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_TRIGGERED, state.state) + assert STATE_ALARM_TRIGGERED == state.state def test_disarm_with_template_code(self): """Attempt to disarm with a valid or invalid template-based code.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual_mqtt', @@ -1221,33 +1221,33 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): 'disarm_after_trigger': False, 'command_topic': 'alarm/command', 'state_topic': 'alarm/state', - }})) + }}) entity_id = 'alarm_control_panel.test' self.hass.start() self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_arm_home(self.hass, 'def') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_ARMED_HOME, state.state) + assert STATE_ALARM_ARMED_HOME == state.state common.alarm_disarm(self.hass, 'def') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_ARMED_HOME, state.state) + assert STATE_ALARM_ARMED_HOME == state.state common.alarm_disarm(self.hass, 'abc') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(STATE_ALARM_DISARMED, state.state) + assert STATE_ALARM_DISARMED == state.state def test_arm_home_via_command_topic(self): """Test arming home via command topic.""" @@ -1264,14 +1264,14 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state # Fire the arm command via MQTT; ensure state changes to pending fire_mqtt_message(self.hass, 'alarm/command', 'ARM_HOME') self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state # Fast-forward a little bit future = dt_util.utcnow() + timedelta(seconds=1) @@ -1280,8 +1280,8 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_HOME, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_HOME == \ + self.hass.states.get(entity_id).state def test_arm_away_via_command_topic(self): """Test arming away via command topic.""" @@ -1298,14 +1298,14 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state # Fire the arm command via MQTT; ensure state changes to pending fire_mqtt_message(self.hass, 'alarm/command', 'ARM_AWAY') self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state # Fast-forward a little bit future = dt_util.utcnow() + timedelta(seconds=1) @@ -1314,8 +1314,8 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_AWAY, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_AWAY == \ + self.hass.states.get(entity_id).state def test_arm_night_via_command_topic(self): """Test arming night via command topic.""" @@ -1332,14 +1332,14 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state # Fire the arm command via MQTT; ensure state changes to pending fire_mqtt_message(self.hass, 'alarm/command', 'ARM_NIGHT') self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state # Fast-forward a little bit future = dt_util.utcnow() + timedelta(seconds=1) @@ -1348,8 +1348,8 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_ARMED_NIGHT, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_ARMED_NIGHT == \ + self.hass.states.get(entity_id).state def test_disarm_pending_via_command_topic(self): """Test disarming pending alarm via command topic.""" @@ -1366,21 +1366,21 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase): entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state common.alarm_trigger(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_ALARM_PENDING, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_PENDING == \ + self.hass.states.get(entity_id).state # Now that we're pending, receive a command to disarm fire_mqtt_message(self.hass, 'alarm/command', 'DISARM') self.hass.block_till_done() - self.assertEqual(STATE_ALARM_DISARMED, - self.hass.states.get(entity_id).state) + assert STATE_ALARM_DISARMED == \ + self.hass.states.get(entity_id).state def test_state_changes_are_published_to_mqtt(self): """Test publishing of MQTT messages when state changes.""" diff --git a/tests/components/alarm_control_panel/test_mqtt.py b/tests/components/alarm_control_panel/test_mqtt.py index dd606bb53..646167181 100644 --- a/tests/components/alarm_control_panel/test_mqtt.py +++ b/tests/components/alarm_control_panel/test_mqtt.py @@ -65,15 +65,15 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_UNKNOWN, - self.hass.states.get(entity_id).state) + assert STATE_UNKNOWN == \ + self.hass.states.get(entity_id).state for state in (STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_AWAY, STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED): fire_mqtt_message(self.hass, 'alarm/state', state) self.hass.block_till_done() - self.assertEqual(state, self.hass.states.get(entity_id).state) + assert state == self.hass.states.get(entity_id).state def test_ignore_update_state_if_unknown_via_state_topic(self): """Test ignoring updates via state topic.""" @@ -88,12 +88,12 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): entity_id = 'alarm_control_panel.test' - self.assertEqual(STATE_UNKNOWN, - self.hass.states.get(entity_id).state) + assert STATE_UNKNOWN == \ + self.hass.states.get(entity_id).state fire_mqtt_message(self.hass, 'alarm/state', 'unsupported state') self.hass.block_till_done() - self.assertEqual(STATE_UNKNOWN, self.hass.states.get(entity_id).state) + assert STATE_UNKNOWN == self.hass.states.get(entity_id).state def test_arm_home_publishes_mqtt(self): """Test publishing of MQTT messages while armed.""" @@ -126,7 +126,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): call_count = self.mock_publish.call_count common.alarm_arm_home(self.hass, 'abcd') self.hass.block_till_done() - self.assertEqual(call_count, self.mock_publish.call_count) + assert call_count == self.mock_publish.call_count def test_arm_away_publishes_mqtt(self): """Test publishing of MQTT messages while armed.""" @@ -159,7 +159,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): call_count = self.mock_publish.call_count common.alarm_arm_away(self.hass, 'abcd') self.hass.block_till_done() - self.assertEqual(call_count, self.mock_publish.call_count) + assert call_count == self.mock_publish.call_count def test_disarm_publishes_mqtt(self): """Test publishing of MQTT messages while disarmed.""" @@ -192,7 +192,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): call_count = self.mock_publish.call_count common.alarm_disarm(self.hass, 'abcd') self.hass.block_till_done() - self.assertEqual(call_count, self.mock_publish.call_count) + assert call_count == self.mock_publish.call_count def test_default_availability_payload(self): """Test availability by default payload with defined topic.""" @@ -208,19 +208,19 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): }) state = self.hass.states.get('alarm_control_panel.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'online') self.hass.block_till_done() state = self.hass.states.get('alarm_control_panel.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'offline') self.hass.block_till_done() state = self.hass.states.get('alarm_control_panel.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def test_custom_availability_payload(self): """Test availability by custom payload with defined topic.""" @@ -238,7 +238,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): }) state = self.hass.states.get('alarm_control_panel.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'good') diff --git a/tests/components/automation/test_event.py b/tests/components/automation/test_event.py index 09d237013..b925e5a80 100644 --- a/tests/components/automation/test_event.py +++ b/tests/components/automation/test_event.py @@ -48,7 +48,7 @@ class TestAutomationEvent(unittest.TestCase): self.hass.bus.fire('test_event', context=context) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) assert self.calls[0].context is context common.turn_off(self.hass) @@ -56,7 +56,7 @@ class TestAutomationEvent(unittest.TestCase): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_event_extra_data(self): """Test the firing of events still matches with event data.""" @@ -74,14 +74,14 @@ class TestAutomationEvent(unittest.TestCase): self.hass.bus.fire('test_event', {'extra_key': 'extra_data'}) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) common.turn_off(self.hass) self.hass.block_till_done() self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_event_with_data(self): """Test the firing of events with data.""" @@ -101,7 +101,7 @@ class TestAutomationEvent(unittest.TestCase): self.hass.bus.fire('test_event', {'some_attr': 'some_value', 'another': 'value'}) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_event_with_empty_data_config(self): """Test the firing of events with empty data config. @@ -125,7 +125,7 @@ class TestAutomationEvent(unittest.TestCase): self.hass.bus.fire('test_event', {'some_attr': 'some_value', 'another': 'value'}) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_event_with_nested_data(self): """Test the firing of events with nested data.""" @@ -153,7 +153,7 @@ class TestAutomationEvent(unittest.TestCase): } }) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_if_event_data_not_matches(self): """Test firing of event if no match.""" @@ -172,4 +172,4 @@ class TestAutomationEvent(unittest.TestCase): self.hass.bus.fire('test_event', {'some_attr': 'some_other_value'}) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) diff --git a/tests/components/automation/test_geo_location.py b/tests/components/automation/test_geo_location.py index 130cdeef9..f14ea34d2 100644 --- a/tests/components/automation/test_geo_location.py +++ b/tests/components/automation/test_geo_location.py @@ -75,11 +75,10 @@ class TestAutomationGeoLocation(unittest.TestCase): }, context=context) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) assert self.calls[0].context is context - self.assertEqual( - 'geo_location - geo_location.entity - hello - hello - test', - self.calls[0].data['some']) + assert 'geo_location - geo_location.entity - hello - hello - test' == \ + self.calls[0].data['some'] # Set out of zone again so we can trigger call self.hass.states.set('geo_location.entity', 'hello', { @@ -97,7 +96,7 @@ class TestAutomationGeoLocation(unittest.TestCase): }) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_for_enter_on_zone_leave(self): """Test for not firing on zone leave.""" @@ -128,7 +127,7 @@ class TestAutomationGeoLocation(unittest.TestCase): }) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_fires_on_zone_leave(self): """Test for firing on zone leave.""" @@ -160,7 +159,7 @@ class TestAutomationGeoLocation(unittest.TestCase): }) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_for_leave_on_zone_enter(self): """Test for not firing on zone enter.""" @@ -191,7 +190,7 @@ class TestAutomationGeoLocation(unittest.TestCase): }) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_fires_on_zone_appear(self): """Test for firing if entity appears in zone.""" @@ -225,11 +224,10 @@ class TestAutomationGeoLocation(unittest.TestCase): }, context=context) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) assert self.calls[0].context is context - self.assertEqual( - 'geo_location - geo_location.entity - - hello - test', - self.calls[0].data['some']) + assert 'geo_location - geo_location.entity - - hello - test' == \ + self.calls[0].data['some'] def test_if_fires_on_zone_disappear(self): """Test for firing if entity disappears from zone.""" @@ -265,7 +263,6 @@ class TestAutomationGeoLocation(unittest.TestCase): self.hass.states.async_remove('geo_location.entity') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual( - 'geo_location - geo_location.entity - hello - - test', - self.calls[0].data['some']) + assert 1 == len(self.calls) + assert 'geo_location - geo_location.entity - hello - - test' == \ + self.calls[0].data['some'] diff --git a/tests/components/automation/test_init.py b/tests/components/automation/test_init.py index 3bcbc7da0..015c31887 100644 --- a/tests/components/automation/test_init.py +++ b/tests/components/automation/test_init.py @@ -152,9 +152,9 @@ class TestAutomation(unittest.TestCase): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual(['hello.world'], - self.calls[0].data.get(ATTR_ENTITY_ID)) + assert 1 == len(self.calls) + assert ['hello.world'] == \ + self.calls[0].data.get(ATTR_ENTITY_ID) def test_service_specify_entity_id_list(self): """Test service data.""" @@ -173,9 +173,9 @@ class TestAutomation(unittest.TestCase): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual(['hello.world', 'hello.world2'], - self.calls[0].data.get(ATTR_ENTITY_ID)) + assert 1 == len(self.calls) + assert ['hello.world', 'hello.world2'] == \ + self.calls[0].data.get(ATTR_ENTITY_ID) def test_two_triggers(self): """Test triggers.""" @@ -199,10 +199,10 @@ class TestAutomation(unittest.TestCase): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) self.hass.states.set('test.entity', 'hello') self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) def test_trigger_service_ignoring_condition(self): """Test triggers.""" @@ -268,21 +268,21 @@ class TestAutomation(unittest.TestCase): self.hass.states.set(entity_id, 100) self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) self.hass.states.set(entity_id, 101) self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) self.hass.states.set(entity_id, 151) self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_automation_list_setting(self): """Event is not a valid condition.""" - self.assertTrue(setup_component(self.hass, automation.DOMAIN, { + assert setup_component(self.hass, automation.DOMAIN, { automation.DOMAIN: [{ 'trigger': { 'platform': 'event', @@ -301,19 +301,19 @@ class TestAutomation(unittest.TestCase): 'service': 'test.automation', } }] - })) + }) self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) self.hass.bus.fire('test_event_2') self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) def test_automation_calling_two_actions(self): """Test if we can call two actions from automation definition.""" - self.assertTrue(setup_component(self.hass, automation.DOMAIN, { + assert setup_component(self.hass, automation.DOMAIN, { automation.DOMAIN: { 'trigger': { 'platform': 'event', @@ -328,7 +328,7 @@ class TestAutomation(unittest.TestCase): 'data': {'position': 1}, }], } - })) + }) self.hass.bus.fire('test_event') self.hass.block_till_done() diff --git a/tests/components/automation/test_mqtt.py b/tests/components/automation/test_mqtt.py index 29a53467c..2d43c4a6d 100644 --- a/tests/components/automation/test_mqtt.py +++ b/tests/components/automation/test_mqtt.py @@ -53,15 +53,15 @@ class TestAutomationMQTT(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', '{ "hello": "world" }') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('mqtt - test-topic - { "hello": "world" } - world', - self.calls[0].data['some']) + assert 1 == len(self.calls) + assert 'mqtt - test-topic - { "hello": "world" } - world' == \ + self.calls[0].data['some'] common.turn_off(self.hass) self.hass.block_till_done() fire_mqtt_message(self.hass, 'test-topic', 'test_payload') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_topic_and_payload_match(self): """Test if message is fired on topic and payload match.""" @@ -80,7 +80,7 @@ class TestAutomationMQTT(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', 'hello') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_on_topic_but_no_payload_match(self): """Test if message is not fired on topic but no payload.""" @@ -99,4 +99,4 @@ class TestAutomationMQTT(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', 'no-hello') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) diff --git a/tests/components/automation/test_numeric_state.py b/tests/components/automation/test_numeric_state.py index 183d1f4a5..f7124be9d 100644 --- a/tests/components/automation/test_numeric_state.py +++ b/tests/components/automation/test_numeric_state.py @@ -53,7 +53,7 @@ class TestAutomationNumericState(unittest.TestCase): # 9 is below 10 self.hass.states.set('test.entity', 9, context=context) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) assert self.calls[0].context is context # Set above 12 so the automation will fire again @@ -62,7 +62,7 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.block_till_done() self.hass.states.set('test.entity', 9) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entity_change_over_to_below(self): """Test the firing with changed entity.""" @@ -85,7 +85,7 @@ class TestAutomationNumericState(unittest.TestCase): # 9 is below 10 self.hass.states.set('test.entity', 9) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entities_change_over_to_below(self): """Test the firing with changed entities.""" @@ -112,10 +112,10 @@ class TestAutomationNumericState(unittest.TestCase): # 9 is below 10 self.hass.states.set('test.entity_1', 9) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) self.hass.states.set('test.entity_2', 9) self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) def test_if_not_fires_on_entity_change_below_to_below(self): """Test the firing with changed entity.""" @@ -139,18 +139,18 @@ class TestAutomationNumericState(unittest.TestCase): # 9 is below 10 so this should fire self.hass.states.set('test.entity', 9, context=context) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) assert self.calls[0].context is context # already below so should not fire again self.hass.states.set('test.entity', 5) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) # still below so should not fire again self.hass.states.set('test.entity', 3) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_below_fires_on_entity_change_to_equal(self): """Test the firing with changed entity.""" @@ -173,7 +173,7 @@ class TestAutomationNumericState(unittest.TestCase): # 10 is not below 10 so this should not fire again self.hass.states.set('test.entity', 10) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_fires_on_initial_entity_below(self): """Test the firing when starting with a match.""" @@ -196,7 +196,7 @@ class TestAutomationNumericState(unittest.TestCase): # Fire on first update even if initial state was already below self.hass.states.set('test.entity', 8) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_initial_entity_above(self): """Test the firing when starting with a match.""" @@ -219,7 +219,7 @@ class TestAutomationNumericState(unittest.TestCase): # Fire on first update even if initial state was already above self.hass.states.set('test.entity', 12) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entity_change_above(self): """Test the firing with changed entity.""" @@ -238,7 +238,7 @@ class TestAutomationNumericState(unittest.TestCase): # 11 is above 10 self.hass.states.set('test.entity', 11) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entity_change_below_to_above(self): """Test the firing with changed entity.""" @@ -262,7 +262,7 @@ class TestAutomationNumericState(unittest.TestCase): # 11 is above 10 and 9 is below self.hass.states.set('test.entity', 11) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_on_entity_change_above_to_above(self): """Test the firing with changed entity.""" @@ -286,12 +286,12 @@ class TestAutomationNumericState(unittest.TestCase): # 12 is above 10 so this should fire self.hass.states.set('test.entity', 12) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) # already above, should not fire again self.hass.states.set('test.entity', 15) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_above_fires_on_entity_change_to_equal(self): """Test the firing with changed entity.""" @@ -315,7 +315,7 @@ class TestAutomationNumericState(unittest.TestCase): # 10 is not above 10 so this should not fire again self.hass.states.set('test.entity', 10) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_fires_on_entity_change_below_range(self): """Test the firing with changed entity.""" @@ -335,7 +335,7 @@ class TestAutomationNumericState(unittest.TestCase): # 9 is below 10 self.hass.states.set('test.entity', 9) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entity_change_below_above_range(self): """Test the firing with changed entity.""" @@ -355,7 +355,7 @@ class TestAutomationNumericState(unittest.TestCase): # 4 is below 5 self.hass.states.set('test.entity', 4) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_fires_on_entity_change_over_to_below_range(self): """Test the firing with changed entity.""" @@ -379,7 +379,7 @@ class TestAutomationNumericState(unittest.TestCase): # 9 is below 10 self.hass.states.set('test.entity', 9) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entity_change_over_to_below_above_range(self): """Test the firing with changed entity.""" @@ -403,7 +403,7 @@ class TestAutomationNumericState(unittest.TestCase): # 4 is below 5 so it should not fire self.hass.states.set('test.entity', 4) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_not_fires_if_entity_not_match(self): """Test if not fired with non matching entity.""" @@ -422,7 +422,7 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.states.set('test.entity', 11) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_fires_on_entity_change_below_with_attribute(self): """Test attributes change.""" @@ -441,7 +441,7 @@ class TestAutomationNumericState(unittest.TestCase): # 9 is below 10 self.hass.states.set('test.entity', 9, {'test_attribute': 11}) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_on_entity_change_not_below_with_attribute(self): """Test attributes.""" @@ -460,7 +460,7 @@ class TestAutomationNumericState(unittest.TestCase): # 11 is not below 10 self.hass.states.set('test.entity', 11, {'test_attribute': 9}) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_fires_on_attribute_change_with_attribute_below(self): """Test attributes change.""" @@ -480,7 +480,7 @@ class TestAutomationNumericState(unittest.TestCase): # 9 is below 10 self.hass.states.set('test.entity', 'entity', {'test_attribute': 9}) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_on_attribute_change_with_attribute_not_below(self): """Test attributes change.""" @@ -500,7 +500,7 @@ class TestAutomationNumericState(unittest.TestCase): # 11 is not below 10 self.hass.states.set('test.entity', 'entity', {'test_attribute': 11}) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_not_fires_on_entity_change_with_attribute_below(self): """Test attributes change.""" @@ -520,7 +520,7 @@ class TestAutomationNumericState(unittest.TestCase): # 11 is not below 10, entity state value should not be tested self.hass.states.set('test.entity', '9', {'test_attribute': 11}) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_not_fires_on_entity_change_with_not_attribute_below(self): """Test attributes change.""" @@ -540,7 +540,7 @@ class TestAutomationNumericState(unittest.TestCase): # 11 is not below 10, entity state value should not be tested self.hass.states.set('test.entity', 'entity') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_fires_on_attr_change_with_attribute_below_and_multiple_attr(self): """Test attributes change.""" @@ -561,7 +561,7 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.states.set('test.entity', 'entity', {'test_attribute': 9, 'not_test_attribute': 11}) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_template_list(self): """Test template list.""" @@ -583,7 +583,7 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.states.set('test.entity', 'entity', {'test_attribute': [11, 15, 3]}) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_template_string(self): """Test template string.""" @@ -612,11 +612,10 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.states.set('test.entity', 'test state 2', {'test_attribute': '0.9'}) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual( - 'numeric_state - test.entity - 10.0 - None - test state 1 - ' - 'test state 2', - self.calls[0].data['some']) + assert 1 == len(self.calls) + assert 'numeric_state - test.entity - 10.0 - None - test state 1 - ' \ + 'test state 2' == \ + self.calls[0].data['some'] def test_not_fires_on_attr_change_with_attr_not_below_multiple_attr(self): """Test if not fired changed attributes.""" @@ -637,7 +636,7 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.states.set('test.entity', 'entity', {'test_attribute': 11, 'not_test_attribute': 9}) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_action(self): """Test if action.""" @@ -664,19 +663,19 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) self.hass.states.set(entity_id, 8) self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) self.hass.states.set(entity_id, 9) self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) def test_if_fails_setup_bad_for(self): """Test for setup failure for bad for.""" @@ -739,7 +738,7 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.block_till_done() fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10)) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_not_fires_on_entities_change_with_for_after_stop(self): """Test for not firing on entities change with for after stop.""" @@ -768,7 +767,7 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.block_till_done() fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10)) self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) self.hass.states.set('test.entity_1', 15) self.hass.states.set('test.entity_2', 15) @@ -781,7 +780,7 @@ class TestAutomationNumericState(unittest.TestCase): fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10)) self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) def test_if_fires_on_entity_change_with_for_attribute_change(self): """Test for firing on entity change with for and attribute change.""" @@ -812,11 +811,11 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.states.set('test.entity', 9, attributes={"mock_attr": "attr_change"}) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) mock_utcnow.return_value += timedelta(seconds=4) fire_time_changed(self.hass, mock_utcnow.return_value) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entity_change_with_for(self): """Test for firing on entity change with for.""" @@ -841,7 +840,7 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.block_till_done() fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_wait_template_with_trigger(self): """Test using wait template with 'trigger.entity_id'.""" @@ -872,7 +871,6 @@ class TestAutomationNumericState(unittest.TestCase): self.hass.block_till_done() self.hass.states.set('test.entity', '8') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual( - 'numeric_state - test.entity - 12', - self.calls[0].data['some']) + assert 1 == len(self.calls) + assert 'numeric_state - test.entity - 12' == \ + self.calls[0].data['some'] diff --git a/tests/components/automation/test_state.py b/tests/components/automation/test_state.py index 15c6353b2..599816ac7 100644 --- a/tests/components/automation/test_state.py +++ b/tests/components/automation/test_state.py @@ -63,17 +63,16 @@ class TestAutomationState(unittest.TestCase): self.hass.states.set('test.entity', 'world', context=context) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) assert self.calls[0].context is context - self.assertEqual( - 'state - test.entity - hello - world - None', - self.calls[0].data['some']) + assert 'state - test.entity - hello - world - None' == \ + self.calls[0].data['some'] common.turn_off(self.hass) self.hass.block_till_done() self.hass.states.set('test.entity', 'planet') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entity_change_with_from_filter(self): """Test for firing on entity change with filter.""" @@ -92,7 +91,7 @@ class TestAutomationState(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entity_change_with_to_filter(self): """Test for firing on entity change with no filter.""" @@ -111,7 +110,7 @@ class TestAutomationState(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_attribute_change_with_to_filter(self): """Test for not firing on attribute change.""" @@ -131,7 +130,7 @@ class TestAutomationState(unittest.TestCase): self.hass.states.set('test.entity', 'world', {'test_attribute': 11}) self.hass.states.set('test.entity', 'world', {'test_attribute': 12}) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entity_change_with_both_filters(self): """Test for firing if both filters are a non match.""" @@ -151,7 +150,7 @@ class TestAutomationState(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_if_to_filter_not_match(self): """Test for not firing if to filter is not a match.""" @@ -171,7 +170,7 @@ class TestAutomationState(unittest.TestCase): self.hass.states.set('test.entity', 'moon') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_not_fires_if_from_filter_not_match(self): """Test for not firing if from filter is not a match.""" @@ -193,7 +192,7 @@ class TestAutomationState(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_not_fires_if_entity_not_match(self): """Test for not firing if entity is not matching.""" @@ -211,7 +210,7 @@ class TestAutomationState(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_action(self): """Test for to action.""" @@ -238,13 +237,13 @@ class TestAutomationState(unittest.TestCase): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) self.hass.states.set(entity_id, test_state + 'something') self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fails_setup_if_to_boolean_value(self): """Test for setup failure for boolean to.""" @@ -335,7 +334,7 @@ class TestAutomationState(unittest.TestCase): self.hass.block_till_done() fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10)) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_not_fires_on_entities_change_with_for_after_stop(self): """Test for not firing on entity change with for after stop trigger.""" @@ -363,7 +362,7 @@ class TestAutomationState(unittest.TestCase): self.hass.block_till_done() fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10)) self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) self.hass.states.set('test.entity_1', 'world_no') self.hass.states.set('test.entity_2', 'world_no') @@ -376,7 +375,7 @@ class TestAutomationState(unittest.TestCase): fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10)) self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) def test_if_fires_on_entity_change_with_for_attribute_change(self): """Test for firing on entity change with for and attribute change.""" @@ -406,11 +405,11 @@ class TestAutomationState(unittest.TestCase): self.hass.states.set('test.entity', 'world', attributes={"mock_attr": "attr_change"}) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) mock_utcnow.return_value += timedelta(seconds=4) fire_time_changed(self.hass, mock_utcnow.return_value) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entity_change_with_for_multiple_force_update(self): """Test for firing on entity change with for and force update.""" @@ -440,11 +439,11 @@ class TestAutomationState(unittest.TestCase): fire_time_changed(self.hass, mock_utcnow.return_value) self.hass.states.set('test.force_entity', 'world', None, True) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) mock_utcnow.return_value += timedelta(seconds=4) fire_time_changed(self.hass, mock_utcnow.return_value) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_entity_change_with_for(self): """Test for firing on entity change with for.""" @@ -468,7 +467,7 @@ class TestAutomationState(unittest.TestCase): self.hass.block_till_done() fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_for_condition(self): """Test for firing if condition is on.""" @@ -498,13 +497,13 @@ class TestAutomationState(unittest.TestCase): # not enough time has passed self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) # Time travel 10 secs into the future mock_utcnow.return_value = point2 self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_for_condition_attribute_change(self): """Test for firing if condition is on with attribute change.""" @@ -535,7 +534,7 @@ class TestAutomationState(unittest.TestCase): # not enough time has passed self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) # Still not enough time has passed, but an attribute is changed mock_utcnow.return_value = point2 @@ -543,13 +542,13 @@ class TestAutomationState(unittest.TestCase): attributes={"mock_attr": "attr_change"}) self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) # Enough time has now passed mock_utcnow.return_value = point3 self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fails_setup_for_without_time(self): """Test for setup failure if no time is provided.""" @@ -615,7 +614,6 @@ class TestAutomationState(unittest.TestCase): self.hass.block_till_done() self.hass.states.set('test.entity', 'hello') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual( - 'state - test.entity - hello - world', - self.calls[0].data['some']) + assert 1 == len(self.calls) + assert 'state - test.entity - hello - world' == \ + self.calls[0].data['some'] diff --git a/tests/components/automation/test_sun.py b/tests/components/automation/test_sun.py index ad8709fdf..3eb30b559 100644 --- a/tests/components/automation/test_sun.py +++ b/tests/components/automation/test_sun.py @@ -63,7 +63,7 @@ class TestAutomationSun(unittest.TestCase): fire_time_changed(self.hass, trigger_time) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) with patch('homeassistant.util.dt.utcnow', return_value=now): @@ -72,7 +72,7 @@ class TestAutomationSun(unittest.TestCase): fire_time_changed(self.hass, trigger_time) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_sunrise_trigger(self): """Test the sunrise trigger.""" @@ -95,7 +95,7 @@ class TestAutomationSun(unittest.TestCase): fire_time_changed(self.hass, trigger_time) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_sunset_trigger_with_offset(self): """Test the sunset trigger with offset.""" @@ -124,8 +124,8 @@ class TestAutomationSun(unittest.TestCase): fire_time_changed(self.hass, trigger_time) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('sun - sunset - 0:30:00', self.calls[0].data['some']) + assert 1 == len(self.calls) + assert 'sun - sunset - 0:30:00' == self.calls[0].data['some'] def test_sunrise_trigger_with_offset(self): """Test the sunrise trigger with offset.""" @@ -149,7 +149,7 @@ class TestAutomationSun(unittest.TestCase): fire_time_changed(self.hass, trigger_time) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_action_before(self): """Test if action was before.""" @@ -174,14 +174,14 @@ class TestAutomationSun(unittest.TestCase): return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) now = datetime(2015, 9, 16, 10, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.utcnow', return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_action_after(self): """Test if action was after.""" @@ -206,14 +206,14 @@ class TestAutomationSun(unittest.TestCase): return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) now = datetime(2015, 9, 16, 15, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.utcnow', return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_action_before_with_offset(self): """Test if action was before offset.""" @@ -239,14 +239,14 @@ class TestAutomationSun(unittest.TestCase): return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) now = datetime(2015, 9, 16, 14, 32, 43, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.utcnow', return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_action_after_with_offset(self): """Test if action was after offset.""" @@ -272,14 +272,14 @@ class TestAutomationSun(unittest.TestCase): return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) now = datetime(2015, 9, 16, 14, 32, 43, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.utcnow', return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_action_before_and_after_during(self): """Test if action was before and after during.""" @@ -305,18 +305,18 @@ class TestAutomationSun(unittest.TestCase): return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) now = datetime(2015, 9, 17, 2, 25, 18, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.utcnow', return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) now = datetime(2015, 9, 16, 16, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.utcnow', return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) diff --git a/tests/components/automation/test_template.py b/tests/components/automation/test_template.py index 4fec0e707..9945677c1 100644 --- a/tests/components/automation/test_template.py +++ b/tests/components/automation/test_template.py @@ -48,14 +48,14 @@ class TestAutomationTemplate(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) common.turn_off(self.hass) self.hass.block_till_done() self.hass.states.set('test.entity', 'planet') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_change_str(self): """Test for firing on change.""" @@ -73,7 +73,7 @@ class TestAutomationTemplate(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_change_str_crazy(self): """Test for firing on change.""" @@ -91,7 +91,7 @@ class TestAutomationTemplate(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_on_change_bool(self): """Test for not firing on boolean change.""" @@ -109,7 +109,7 @@ class TestAutomationTemplate(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_not_fires_on_change_str(self): """Test for not firing on string change.""" @@ -127,7 +127,7 @@ class TestAutomationTemplate(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_not_fires_on_change_str_crazy(self): """Test for not firing on string change.""" @@ -145,7 +145,7 @@ class TestAutomationTemplate(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_fires_on_no_change(self): """Test for firing on no change.""" @@ -166,7 +166,7 @@ class TestAutomationTemplate(unittest.TestCase): self.hass.states.set('test.entity', 'hello') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_fires_on_two_change(self): """Test for firing on two changes.""" @@ -185,12 +185,12 @@ class TestAutomationTemplate(unittest.TestCase): # Trigger once self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) # Trigger again self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_change_with_template(self): """Test for firing on change with template.""" @@ -208,7 +208,7 @@ class TestAutomationTemplate(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_on_change_with_template(self): """Test for not firing on change with template.""" @@ -257,11 +257,10 @@ class TestAutomationTemplate(unittest.TestCase): self.hass.states.set('test.entity', 'world', context=context) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) assert self.calls[0].context is context - self.assertEqual( - 'template - test.entity - hello - world', - self.calls[0].data['some']) + assert 'template - test.entity - hello - world' == \ + self.calls[0].data['some'] def test_if_fires_on_no_change_with_template_advanced(self): """Test for firing on no change with template advanced.""" @@ -284,12 +283,12 @@ class TestAutomationTemplate(unittest.TestCase): # Different state self.hass.states.set('test.entity', 'worldz') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) # Different state self.hass.states.set('test.entity', 'hello') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_fires_on_change_with_template_2(self): """Test for firing on change with template.""" @@ -354,17 +353,17 @@ class TestAutomationTemplate(unittest.TestCase): # Condition is not true yet self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) # Change condition to true, but it shouldn't be triggered yet self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) # Condition is true and event is triggered self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_on_change_with_bad_template(self): """Test for firing on change with bad template.""" @@ -397,7 +396,7 @@ class TestAutomationTemplate(unittest.TestCase): self.hass.states.set('test.entity', 'world') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_wait_template_with_trigger(self): """Test using wait template with 'trigger.entity_id'.""" @@ -429,7 +428,6 @@ class TestAutomationTemplate(unittest.TestCase): self.hass.block_till_done() self.hass.states.set('test.entity', 'hello') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual( - 'template - test.entity - hello - world', - self.calls[0].data['some']) + assert 1 == len(self.calls) + assert 'template - test.entity - hello - world' == \ + self.calls[0].data['some'] diff --git a/tests/components/automation/test_time.py b/tests/components/automation/test_time.py index dcb723d72..d1d9bcaec 100644 --- a/tests/components/automation/test_time.py +++ b/tests/components/automation/test_time.py @@ -51,14 +51,14 @@ class TestAutomationTime(unittest.TestCase): fire_time_changed(self.hass, dt_util.utcnow().replace(hour=0)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) common.turn_off(self.hass) self.hass.block_till_done() fire_time_changed(self.hass, dt_util.utcnow().replace(hour=0)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_when_minute_matches(self): """Test for firing if minutes are matching.""" @@ -77,7 +77,7 @@ class TestAutomationTime(unittest.TestCase): fire_time_changed(self.hass, dt_util.utcnow().replace(minute=0)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_when_second_matches(self): """Test for firing if seconds are matching.""" @@ -96,7 +96,7 @@ class TestAutomationTime(unittest.TestCase): fire_time_changed(self.hass, dt_util.utcnow().replace(second=0)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_when_all_matches(self): """Test for firing if everything matches.""" @@ -118,7 +118,7 @@ class TestAutomationTime(unittest.TestCase): hour=1, minute=2, second=3)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_periodic_seconds(self): """Test for firing periodically every second.""" @@ -138,7 +138,7 @@ class TestAutomationTime(unittest.TestCase): hour=0, minute=0, second=2)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_periodic_minutes(self): """Test for firing periodically every minute.""" @@ -158,7 +158,7 @@ class TestAutomationTime(unittest.TestCase): hour=0, minute=2, second=0)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_periodic_hours(self): """Test for firing periodically every hour.""" @@ -178,7 +178,7 @@ class TestAutomationTime(unittest.TestCase): hour=2, minute=0, second=0)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_fires_using_at(self): """Test for firing at.""" @@ -202,8 +202,8 @@ class TestAutomationTime(unittest.TestCase): hour=5, minute=0, second=0)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('time - 5', self.calls[0].data['some']) + assert 1 == len(self.calls) + assert 'time - 5' == self.calls[0].data['some'] def test_if_not_working_if_no_values_in_conf_provided(self): """Test for failure if no configuration.""" @@ -223,7 +223,7 @@ class TestAutomationTime(unittest.TestCase): hour=5, minute=0, second=0)) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_not_fires_using_wrong_at(self): """YAML translates time values to total seconds. @@ -248,7 +248,7 @@ class TestAutomationTime(unittest.TestCase): hour=1, minute=0, second=5)) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_action_before(self): """Test for if action before.""" @@ -276,14 +276,14 @@ class TestAutomationTime(unittest.TestCase): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) with patch('homeassistant.helpers.condition.dt_util.now', return_value=after_10): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_action_after(self): """Test for if action after.""" @@ -311,14 +311,14 @@ class TestAutomationTime(unittest.TestCase): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) with patch('homeassistant.helpers.condition.dt_util.now', return_value=after_10): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_action_one_weekday(self): """Test for if action with one weekday.""" @@ -347,14 +347,14 @@ class TestAutomationTime(unittest.TestCase): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) with patch('homeassistant.helpers.condition.dt_util.now', return_value=tuesday): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_action_list_weekday(self): """Test for action with a list of weekdays.""" @@ -384,18 +384,18 @@ class TestAutomationTime(unittest.TestCase): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) with patch('homeassistant.helpers.condition.dt_util.now', return_value=tuesday): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) with patch('homeassistant.helpers.condition.dt_util.now', return_value=wednesday): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) diff --git a/tests/components/automation/test_zone.py b/tests/components/automation/test_zone.py index 795f55a3e..d0ab4d726 100644 --- a/tests/components/automation/test_zone.py +++ b/tests/components/automation/test_zone.py @@ -75,11 +75,10 @@ class TestAutomationZone(unittest.TestCase): }, context=context) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) assert self.calls[0].context is context - self.assertEqual( - 'zone - test.entity - hello - hello - test', - self.calls[0].data['some']) + assert 'zone - test.entity - hello - hello - test' == \ + self.calls[0].data['some'] # Set out of zone again so we can trigger call self.hass.states.set('test.entity', 'hello', { @@ -97,7 +96,7 @@ class TestAutomationZone(unittest.TestCase): }) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_for_enter_on_zone_leave(self): """Test for not firing on zone leave.""" @@ -127,7 +126,7 @@ class TestAutomationZone(unittest.TestCase): }) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_if_fires_on_zone_leave(self): """Test for firing on zone leave.""" @@ -157,7 +156,7 @@ class TestAutomationZone(unittest.TestCase): }) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_if_not_fires_for_leave_on_zone_enter(self): """Test for not firing on zone enter.""" @@ -187,7 +186,7 @@ class TestAutomationZone(unittest.TestCase): }) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_zone_condition(self): """Test for zone condition.""" @@ -216,4 +215,4 @@ class TestAutomationZone(unittest.TestCase): self.hass.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) diff --git a/tests/components/binary_sensor/test_aurora.py b/tests/components/binary_sensor/test_aurora.py index 1198aeb13..109da8e8a 100644 --- a/tests/components/binary_sensor/test_aurora.py +++ b/tests/components/binary_sensor/test_aurora.py @@ -50,17 +50,13 @@ class TestAuroraSensorSetUp(unittest.TestCase): aurora.setup_platform(self.hass, config, mock_add_entities) aurora_component = entities[0] - self.assertEqual(len(entities), 1) - self.assertEqual(aurora_component.name, "Test") - self.assertEqual( - aurora_component.device_state_attributes["visibility_level"], - '0' - ) - self.assertEqual( - aurora_component.device_state_attributes["message"], + assert len(entities) == 1 + assert aurora_component.name == "Test" + assert \ + aurora_component.device_state_attributes["visibility_level"] == '0' + assert aurora_component.device_state_attributes["message"] == \ "nothing's out" - ) - self.assertFalse(aurora_component.is_on) + assert not aurora_component.is_on @requests_mock.Mocker() def test_custom_threshold_works(self, mock_req): @@ -91,5 +87,5 @@ class TestAuroraSensorSetUp(unittest.TestCase): aurora.setup_platform(self.hass, config, mock_add_entities) aurora_component = entities[0] - self.assertEqual(aurora_component.aurora_data.visibility_level, '5') - self.assertTrue(aurora_component.is_on) + assert aurora_component.aurora_data.visibility_level == '5' + assert aurora_component.is_on diff --git a/tests/components/binary_sensor/test_bayesian.py b/tests/components/binary_sensor/test_bayesian.py index c3242e09e..b52459ec4 100644 --- a/tests/components/binary_sensor/test_bayesian.py +++ b/tests/components/binary_sensor/test_bayesian.py @@ -52,8 +52,8 @@ class TestBayesianBinarySensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.test_binary') - self.assertEqual([], state.attributes.get('observations')) - self.assertEqual(0.2, state.attributes.get('probability')) + assert [] == state.attributes.get('observations') + assert 0.2 == state.attributes.get('probability') assert state.state == 'off' @@ -66,14 +66,14 @@ class TestBayesianBinarySensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test_binary') - self.assertEqual([{ + assert [{ 'prob_false': 0.4, 'prob_true': 0.6 }, { 'prob_false': 0.1, 'prob_true': 0.9 - }], state.attributes.get('observations')) - self.assertAlmostEqual(0.77, state.attributes.get('probability')) + }] == state.attributes.get('observations') + assert round(abs(0.77-state.attributes.get('probability')), 7) == 0 assert state.state == 'on' @@ -84,7 +84,7 @@ class TestBayesianBinarySensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test_binary') - self.assertEqual(0.2, state.attributes.get('probability')) + assert 0.2 == state.attributes.get('probability') assert state.state == 'off' @@ -123,8 +123,8 @@ class TestBayesianBinarySensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.test_binary') - self.assertEqual([], state.attributes.get('observations')) - self.assertEqual(0.2, state.attributes.get('probability')) + assert [] == state.attributes.get('observations') + assert 0.2 == state.attributes.get('probability') assert state.state == 'off' @@ -136,11 +136,11 @@ class TestBayesianBinarySensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test_binary') - self.assertEqual([{ + assert [{ 'prob_true': 0.8, 'prob_false': 0.4 - }], state.attributes.get('observations')) - self.assertAlmostEqual(0.33, state.attributes.get('probability')) + }] == state.attributes.get('observations') + assert round(abs(0.33-state.attributes.get('probability')), 7) == 0 assert state.state == 'on' @@ -150,7 +150,7 @@ class TestBayesianBinarySensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test_binary') - self.assertAlmostEqual(0.2, state.attributes.get('probability')) + assert round(abs(0.2-state.attributes.get('probability')), 7) == 0 assert state.state == 'off' @@ -181,7 +181,7 @@ class TestBayesianBinarySensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test_binary') - self.assertAlmostEqual(1.0, state.attributes.get('probability')) + assert round(abs(1.0-state.attributes.get('probability')), 7) == 0 assert state.state == 'on' @@ -219,8 +219,8 @@ class TestBayesianBinarySensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.test_binary') - self.assertEqual([], state.attributes.get('observations')) - self.assertEqual(0.2, state.attributes.get('probability')) + assert [] == state.attributes.get('observations') + assert 0.2 == state.attributes.get('probability') assert state.state == 'off' @@ -232,11 +232,11 @@ class TestBayesianBinarySensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test_binary') - self.assertEqual([{ + assert [{ 'prob_true': 0.8, 'prob_false': 0.4 - }], state.attributes.get('observations')) - self.assertAlmostEqual(0.33, state.attributes.get('probability')) + }] == state.attributes.get('observations') + assert round(abs(0.33-state.attributes.get('probability')), 7) == 0 assert state.state == 'on' @@ -246,7 +246,7 @@ class TestBayesianBinarySensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test_binary') - self.assertAlmostEqual(0.11, state.attributes.get('probability')) + assert round(abs(0.11-state.attributes.get('probability')), 7) == 0 assert state.state == 'off' @@ -259,7 +259,7 @@ class TestBayesianBinarySensor(unittest.TestCase): for pt, pf in zip(prob_true, prob_false): prior = bayesian.update_probability(prior, pt, pf) - self.assertAlmostEqual(0.720000, prior) + assert round(abs(0.720000-prior), 7) == 0 prob_true = [0.8, 0.3, 0.9] prob_false = [0.6, 0.4, 0.2] @@ -268,4 +268,4 @@ class TestBayesianBinarySensor(unittest.TestCase): for pt, pf in zip(prob_true, prob_false): prior = bayesian.update_probability(prior, pt, pf) - self.assertAlmostEqual(0.9130434782608695, prior) + assert round(abs(0.9130434782608695-prior), 7) == 0 diff --git a/tests/components/binary_sensor/test_binary_sensor.py b/tests/components/binary_sensor/test_binary_sensor.py index 89b6226c0..050af3e2c 100644 --- a/tests/components/binary_sensor/test_binary_sensor.py +++ b/tests/components/binary_sensor/test_binary_sensor.py @@ -12,14 +12,14 @@ class TestBinarySensor(unittest.TestCase): def test_state(self): """Test binary sensor state.""" sensor = binary_sensor.BinarySensorDevice() - self.assertEqual(STATE_OFF, sensor.state) + assert STATE_OFF == sensor.state with mock.patch('homeassistant.components.binary_sensor.' 'BinarySensorDevice.is_on', new=False): - self.assertEqual(STATE_OFF, - binary_sensor.BinarySensorDevice().state) + assert STATE_OFF == \ + binary_sensor.BinarySensorDevice().state with mock.patch('homeassistant.components.binary_sensor.' 'BinarySensorDevice.is_on', new=True): - self.assertEqual(STATE_ON, - binary_sensor.BinarySensorDevice().state) + assert STATE_ON == \ + binary_sensor.BinarySensorDevice().state diff --git a/tests/components/binary_sensor/test_command_line.py b/tests/components/binary_sensor/test_command_line.py index d469fc65e..2a6b35ea5 100644 --- a/tests/components/binary_sensor/test_command_line.py +++ b/tests/components/binary_sensor/test_command_line.py @@ -37,11 +37,11 @@ class TestCommandSensorBinarySensor(unittest.TestCase): command_line.setup_platform(self.hass, config, add_dev_callback) - self.assertEqual(1, len(devices)) + assert 1 == len(devices) entity = devices[0] entity.update() - self.assertEqual('Test', entity.name) - self.assertEqual(STATE_ON, entity.state) + assert 'Test' == entity.name + assert STATE_ON == entity.state def test_template(self): """Test setting the state with a template.""" @@ -51,7 +51,7 @@ class TestCommandSensorBinarySensor(unittest.TestCase): self.hass, data, 'test', None, '1.0', '0', template.Template('{{ value | multiply(0.1) }}', self.hass)) entity.update() - self.assertEqual(STATE_ON, entity.state) + assert STATE_ON == entity.state def test_sensor_off(self): """Test setting the state with a template.""" @@ -60,4 +60,4 @@ class TestCommandSensorBinarySensor(unittest.TestCase): entity = command_line.CommandBinarySensor( self.hass, data, 'test', None, '1', '0', None) entity.update() - self.assertEqual(STATE_OFF, entity.state) + assert STATE_OFF == entity.state diff --git a/tests/components/binary_sensor/test_mqtt.py b/tests/components/binary_sensor/test_mqtt.py index 8e9e7dcf3..d49bbb329 100644 --- a/tests/components/binary_sensor/test_mqtt.py +++ b/tests/components/binary_sensor/test_mqtt.py @@ -46,17 +46,17 @@ class TestSensorMQTT(unittest.TestCase): }) state = self.hass.states.get('binary_sensor.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state fire_mqtt_message(self.hass, 'test-topic', 'ON') self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state fire_mqtt_message(self.hass, 'test-topic', 'OFF') self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state def test_valid_device_class(self): """Test the setting of a valid sensor class.""" @@ -70,7 +70,7 @@ class TestSensorMQTT(unittest.TestCase): }) state = self.hass.states.get('binary_sensor.test') - self.assertEqual('motion', state.attributes.get('device_class')) + assert 'motion' == state.attributes.get('device_class') def test_invalid_device_class(self): """Test the setting of an invalid sensor class.""" @@ -84,50 +84,50 @@ class TestSensorMQTT(unittest.TestCase): }) state = self.hass.states.get('binary_sensor.test') - self.assertIsNone(state) + assert state is None def test_availability_without_topic(self): """Test availability without defined availability topic.""" - self.assertTrue(setup_component(self.hass, binary_sensor.DOMAIN, { + assert setup_component(self.hass, binary_sensor.DOMAIN, { binary_sensor.DOMAIN: { 'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', } - })) + }) state = self.hass.states.get('binary_sensor.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state def test_availability_by_defaults(self): """Test availability by defaults with defined topic.""" - self.assertTrue(setup_component(self.hass, binary_sensor.DOMAIN, { + assert setup_component(self.hass, binary_sensor.DOMAIN, { binary_sensor.DOMAIN: { 'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'availability_topic': 'availability-topic' } - })) + }) state = self.hass.states.get('binary_sensor.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'online') self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'offline') self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def test_availability_by_custom_payload(self): """Test availability by custom payload with defined topic.""" - self.assertTrue(setup_component(self.hass, binary_sensor.DOMAIN, { + assert setup_component(self.hass, binary_sensor.DOMAIN, { binary_sensor.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -136,22 +136,22 @@ class TestSensorMQTT(unittest.TestCase): 'payload_available': 'good', 'payload_not_available': 'nogood' } - })) + }) state = self.hass.states.get('binary_sensor.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'good') self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'nogood') self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def test_force_update_disabled(self): """Test force update option.""" @@ -177,11 +177,11 @@ class TestSensorMQTT(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', 'ON') self.hass.block_till_done() - self.assertEqual(1, len(events)) + assert 1 == len(events) fire_mqtt_message(self.hass, 'test-topic', 'ON') self.hass.block_till_done() - self.assertEqual(1, len(events)) + assert 1 == len(events) def test_force_update_enabled(self): """Test force update option.""" @@ -208,11 +208,11 @@ class TestSensorMQTT(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', 'ON') self.hass.block_till_done() - self.assertEqual(1, len(events)) + assert 1 == len(events) fire_mqtt_message(self.hass, 'test-topic', 'ON') self.hass.block_till_done() - self.assertEqual(2, len(events)) + assert 2 == len(events) def test_off_delay(self): """Test off_delay option.""" @@ -241,20 +241,20 @@ class TestSensorMQTT(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', 'ON') self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(1, len(events)) + assert STATE_ON == state.state + assert 1 == len(events) fire_mqtt_message(self.hass, 'test-topic', 'ON') self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(2, len(events)) + assert STATE_ON == state.state + assert 2 == len(events) fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=30)) self.hass.block_till_done() state = self.hass.states.get('binary_sensor.test') - self.assertEqual(STATE_OFF, state.state) - self.assertEqual(3, len(events)) + assert STATE_OFF == state.state + assert 3 == len(events) async def test_unique_id(hass): diff --git a/tests/components/binary_sensor/test_nx584.py b/tests/components/binary_sensor/test_nx584.py index 252996201..3239ddbc4 100644 --- a/tests/components/binary_sensor/test_nx584.py +++ b/tests/components/binary_sensor/test_nx584.py @@ -9,6 +9,7 @@ from homeassistant.components.binary_sensor import nx584 from homeassistant.setup import setup_component from tests.common import get_test_home_assistant +import pytest class StopMe(Exception): @@ -52,14 +53,13 @@ class TestNX584SensorSetup(unittest.TestCase): 'exclude_zones': [], 'zone_types': {}, } - self.assertTrue(nx584.setup_platform(self.hass, config, add_entities)) + assert nx584.setup_platform(self.hass, config, add_entities) mock_nx.assert_has_calls( [mock.call(zone, 'opening') for zone in self.fake_zones]) - self.assertTrue(add_entities.called) - self.assertEqual(nx584_client.Client.call_count, 1) - self.assertEqual( - nx584_client.Client.call_args, mock.call('http://localhost:5007') - ) + assert add_entities.called + assert nx584_client.Client.call_count == 1 + assert nx584_client.Client.call_args == \ + mock.call('http://localhost:5007') @mock.patch('homeassistant.components.binary_sensor.nx584.NX584Watcher') @mock.patch('homeassistant.components.binary_sensor.nx584.NX584ZoneSensor') @@ -72,22 +72,20 @@ class TestNX584SensorSetup(unittest.TestCase): 'zone_types': {3: 'motion'}, } add_entities = mock.MagicMock() - self.assertTrue(nx584.setup_platform(self.hass, config, add_entities)) + assert nx584.setup_platform(self.hass, config, add_entities) mock_nx.assert_has_calls([ mock.call(self.fake_zones[0], 'opening'), mock.call(self.fake_zones[2], 'motion'), ]) - self.assertTrue(add_entities.called) - self.assertEqual(nx584_client.Client.call_count, 1) - self.assertEqual( - nx584_client.Client.call_args, mock.call('http://foo:123') - ) - self.assertTrue(mock_watcher.called) + assert add_entities.called + assert nx584_client.Client.call_count == 1 + assert nx584_client.Client.call_args == mock.call('http://foo:123') + assert mock_watcher.called def _test_assert_graceful_fail(self, config): """Test the failing.""" - self.assertFalse(setup_component( - self.hass, 'binary_sensor.nx584', config)) + assert not setup_component( + self.hass, 'binary_sensor.nx584', config) def test_setup_bad_config(self): """Test the setup with bad configuration.""" @@ -121,8 +119,8 @@ class TestNX584SensorSetup(unittest.TestCase): """Test the setup with no zones.""" nx584_client.Client.return_value.list_zones.return_value = [] add_entities = mock.MagicMock() - self.assertTrue(nx584.setup_platform(self.hass, {}, add_entities)) - self.assertFalse(add_entities.called) + assert nx584.setup_platform(self.hass, {}, add_entities) + assert not add_entities.called class TestNX584ZoneSensor(unittest.TestCase): @@ -132,12 +130,12 @@ class TestNX584ZoneSensor(unittest.TestCase): """Test the sensor.""" zone = {'number': 1, 'name': 'foo', 'state': True} sensor = nx584.NX584ZoneSensor(zone, 'motion') - self.assertEqual('foo', sensor.name) - self.assertFalse(sensor.should_poll) - self.assertTrue(sensor.is_on) + assert 'foo' == sensor.name + assert not sensor.should_poll + assert sensor.is_on zone['state'] = False - self.assertFalse(sensor.is_on) + assert not sensor.is_on class TestNX584Watcher(unittest.TestCase): @@ -154,15 +152,15 @@ class TestNX584Watcher(unittest.TestCase): } watcher = nx584.NX584Watcher(None, zones) watcher._process_zone_event({'zone': 1, 'zone_state': False}) - self.assertFalse(zone1['state']) - self.assertEqual(1, mock_update.call_count) + assert not zone1['state'] + assert 1 == mock_update.call_count @mock.patch.object(nx584.NX584ZoneSensor, 'schedule_update_ha_state') def test_process_zone_event_missing_zone(self, mock_update): """Test the processing of zone events with missing zones.""" watcher = nx584.NX584Watcher(None, {}) watcher._process_zone_event({'zone': 1, 'zone_state': False}) - self.assertFalse(mock_update.called) + assert not mock_update.called def test_run_with_zone_events(self): """Test the zone events.""" @@ -187,12 +185,13 @@ class TestNX584Watcher(unittest.TestCase): def run(fake_process): """Run a fake process.""" fake_process.side_effect = StopMe - self.assertRaises(StopMe, watcher._run) - self.assertEqual(fake_process.call_count, 1) - self.assertEqual(fake_process.call_args, mock.call(fake_events[0])) + with pytest.raises(StopMe): + watcher._run() + assert fake_process.call_count == 1 + assert fake_process.call_args == mock.call(fake_events[0]) run() - self.assertEqual(3, client.get_events.call_count) + assert 3 == client.get_events.call_count @mock.patch('time.sleep') def test_run_retries_failures(self, mock_sleep): @@ -210,6 +209,7 @@ class TestNX584Watcher(unittest.TestCase): watcher = nx584.NX584Watcher(None, {}) with mock.patch.object(watcher, '_run') as mock_inner: mock_inner.side_effect = fake_run - self.assertRaises(StopMe, watcher.run) - self.assertEqual(3, mock_inner.call_count) + with pytest.raises(StopMe): + watcher.run() + assert 3 == mock_inner.call_count mock_sleep.assert_has_calls([mock.call(10), mock.call(10)]) diff --git a/tests/components/binary_sensor/test_random.py b/tests/components/binary_sensor/test_random.py index 9ec199015..45f2e384b 100644 --- a/tests/components/binary_sensor/test_random.py +++ b/tests/components/binary_sensor/test_random.py @@ -32,7 +32,7 @@ class TestRandomSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.test') - self.assertEqual(state.state, 'on') + assert state.state == 'on' @patch('random.getrandbits', return_value=False) def test_random_binary_sensor_off(self, mocked): @@ -48,4 +48,4 @@ class TestRandomSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.test') - self.assertEqual(state.state, 'off') + assert state.state == 'off' diff --git a/tests/components/binary_sensor/test_rest.py b/tests/components/binary_sensor/test_rest.py index db70303e2..d3df1a32a 100644 --- a/tests/components/binary_sensor/test_rest.py +++ b/tests/components/binary_sensor/test_rest.py @@ -15,6 +15,7 @@ from homeassistant.const import STATE_ON, STATE_OFF from homeassistant.helpers import template from tests.common import get_test_home_assistant, assert_setup_component +import pytest class TestRestBinarySensorSetup(unittest.TestCase): @@ -45,7 +46,7 @@ class TestRestBinarySensorSetup(unittest.TestCase): def test_setup_missing_schema(self): """Test setup with resource missing schema.""" - with self.assertRaises(MissingSchema): + with pytest.raises(MissingSchema): rest.setup_platform(self.hass, { 'platform': 'rest', 'resource': 'localhost', @@ -61,7 +62,7 @@ class TestRestBinarySensorSetup(unittest.TestCase): 'platform': 'rest', 'resource': 'http://localhost', }, self.add_devices, None) - self.assertEqual(len(self.DEVICES), 0) + assert len(self.DEVICES) == 0 @patch('requests.Session.send', side_effect=Timeout()) def test_setup_timeout(self, mock_req): @@ -71,27 +72,27 @@ class TestRestBinarySensorSetup(unittest.TestCase): 'platform': 'rest', 'resource': 'http://localhost', }, self.add_devices, None) - self.assertEqual(len(self.DEVICES), 0) + assert len(self.DEVICES) == 0 @requests_mock.Mocker() def test_setup_minimum(self, mock_req): """Test setup with minimum configuration.""" mock_req.get('http://localhost', status_code=200) with assert_setup_component(1, 'binary_sensor'): - self.assertTrue(setup_component(self.hass, 'binary_sensor', { + assert setup_component(self.hass, 'binary_sensor', { 'binary_sensor': { 'platform': 'rest', 'resource': 'http://localhost' } - })) - self.assertEqual(1, mock_req.call_count) + }) + assert 1 == mock_req.call_count @requests_mock.Mocker() def test_setup_get(self, mock_req): """Test setup with valid configuration.""" mock_req.get('http://localhost', status_code=200) with assert_setup_component(1, 'binary_sensor'): - self.assertTrue(setup_component(self.hass, 'binary_sensor', { + assert setup_component(self.hass, 'binary_sensor', { 'binary_sensor': { 'platform': 'rest', 'resource': 'http://localhost', @@ -105,15 +106,15 @@ class TestRestBinarySensorSetup(unittest.TestCase): 'password': 'my password', 'headers': {'Accept': 'application/json'} } - })) - self.assertEqual(1, mock_req.call_count) + }) + assert 1 == mock_req.call_count @requests_mock.Mocker() def test_setup_post(self, mock_req): """Test setup with valid configuration.""" mock_req.post('http://localhost', status_code=200) with assert_setup_component(1, 'binary_sensor'): - self.assertTrue(setup_component(self.hass, 'binary_sensor', { + assert setup_component(self.hass, 'binary_sensor', { 'binary_sensor': { 'platform': 'rest', 'resource': 'http://localhost', @@ -128,8 +129,8 @@ class TestRestBinarySensorSetup(unittest.TestCase): 'password': 'my password', 'headers': {'Accept': 'application/json'} } - })) - self.assertEqual(1, mock_req.call_count) + }) + assert 1 == mock_req.call_count class TestRestBinarySensor(unittest.TestCase): @@ -161,16 +162,16 @@ class TestRestBinarySensor(unittest.TestCase): def test_name(self): """Test the name.""" - self.assertEqual(self.name, self.binary_sensor.name) + assert self.name == self.binary_sensor.name def test_device_class(self): """Test the device class.""" - self.assertEqual(self.device_class, self.binary_sensor.device_class) + assert self.device_class == self.binary_sensor.device_class def test_initial_state(self): """Test the initial state.""" self.binary_sensor.update() - self.assertEqual(STATE_OFF, self.binary_sensor.state) + assert STATE_OFF == self.binary_sensor.state def test_update_when_value_is_none(self): """Test state gets updated to unknown when sensor returns no data.""" @@ -178,7 +179,7 @@ class TestRestBinarySensor(unittest.TestCase): 'RestData.update', side_effect=self.update_side_effect(None)) self.binary_sensor.update() - self.assertFalse(self.binary_sensor.available) + assert not self.binary_sensor.available def test_update_when_value_changed(self): """Test state gets updated when sensor returns a new status.""" @@ -186,15 +187,15 @@ class TestRestBinarySensor(unittest.TestCase): side_effect=self.update_side_effect( '{ "key": true }')) self.binary_sensor.update() - self.assertEqual(STATE_ON, self.binary_sensor.state) - self.assertTrue(self.binary_sensor.available) + assert STATE_ON == self.binary_sensor.state + assert self.binary_sensor.available def test_update_when_failed_request(self): """Test state gets updated when sensor returns a new status.""" self.rest.update = Mock('rest.RestData.update', side_effect=self.update_side_effect(None)) self.binary_sensor.update() - self.assertFalse(self.binary_sensor.available) + assert not self.binary_sensor.available def test_update_with_no_template(self): """Test update when there is no value template.""" @@ -203,5 +204,5 @@ class TestRestBinarySensor(unittest.TestCase): self.binary_sensor = rest.RestBinarySensor( self.hass, self.rest, self.name, self.device_class, None) self.binary_sensor.update() - self.assertEqual(STATE_ON, self.binary_sensor.state) - self.assertTrue(self.binary_sensor.available) + assert STATE_ON == self.binary_sensor.state + assert self.binary_sensor.available diff --git a/tests/components/binary_sensor/test_ring.py b/tests/components/binary_sensor/test_ring.py index b7564dff4..a4b243e74 100644 --- a/tests/components/binary_sensor/test_ring.py +++ b/tests/components/binary_sensor/test_ring.py @@ -64,13 +64,13 @@ class TestRingBinarySensorSetup(unittest.TestCase): for device in self.DEVICES: device.update() if device.name == 'Front Door Ding': - self.assertEqual('on', device.state) - self.assertEqual('America/New_York', - device.device_state_attributes['timezone']) + assert 'on' == device.state + assert 'America/New_York' == \ + device.device_state_attributes['timezone'] elif device.name == 'Front Door Motion': - self.assertEqual('off', device.state) - self.assertEqual('motion', device.device_class) + assert 'off' == device.state + assert 'motion' == device.device_class - self.assertIsNone(device.entity_picture) - self.assertEqual(ATTRIBUTION, - device.device_state_attributes['attribution']) + assert device.entity_picture is None + assert ATTRIBUTION == \ + device.device_state_attributes['attribution'] diff --git a/tests/components/binary_sensor/test_sleepiq.py b/tests/components/binary_sensor/test_sleepiq.py index 9cd5dfa7f..3f3d69ad9 100644 --- a/tests/components/binary_sensor/test_sleepiq.py +++ b/tests/components/binary_sensor/test_sleepiq.py @@ -47,12 +47,12 @@ class TestSleepIQBinarySensorSetup(unittest.TestCase): self.config, self.add_entities, MagicMock()) - self.assertEqual(2, len(self.DEVICES)) + assert 2 == len(self.DEVICES) left_side = self.DEVICES[1] - self.assertEqual('SleepNumber ILE Test1 Is In Bed', left_side.name) - self.assertEqual('on', left_side.state) + assert 'SleepNumber ILE Test1 Is In Bed' == left_side.name + assert 'on' == left_side.state right_side = self.DEVICES[0] - self.assertEqual('SleepNumber ILE Test2 Is In Bed', right_side.name) - self.assertEqual('off', right_side.state) + assert 'SleepNumber ILE Test2 Is In Bed' == right_side.name + assert 'off' == right_side.state diff --git a/tests/components/binary_sensor/test_template.py b/tests/components/binary_sensor/test_template.py index eba3a368f..7307b2224 100644 --- a/tests/components/binary_sensor/test_template.py +++ b/tests/components/binary_sensor/test_template.py @@ -168,18 +168,18 @@ class TestBinarySensorTemplate(unittest.TestCase): template_hlpr.Template('{{ 1 > 1 }}', self.hass), None, None, MATCH_ALL, None, None ).result() - self.assertFalse(vs.should_poll) - self.assertEqual('motion', vs.device_class) - self.assertEqual('Parent', vs.name) + assert not vs.should_poll + assert 'motion' == vs.device_class + assert 'Parent' == vs.name run_callback_threadsafe(self.hass.loop, vs.async_check_state).result() - self.assertFalse(vs.is_on) + assert not vs.is_on # pylint: disable=protected-access vs._template = template_hlpr.Template("{{ 2 > 1 }}", self.hass) run_callback_threadsafe(self.hass.loop, vs.async_check_state).result() - self.assertTrue(vs.is_on) + assert vs.is_on def test_event(self): """Test the event.""" diff --git a/tests/components/binary_sensor/test_threshold.py b/tests/components/binary_sensor/test_threshold.py index 926b3c679..2537282ed 100644 --- a/tests/components/binary_sensor/test_threshold.py +++ b/tests/components/binary_sensor/test_threshold.py @@ -37,14 +37,14 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('sensor.test_monitored', - state.attributes.get('entity_id')) - self.assertEqual(16, state.attributes.get('sensor_value')) - self.assertEqual('above', state.attributes.get('position')) - self.assertEqual(float(config['binary_sensor']['upper']), - state.attributes.get('upper')) - self.assertEqual(0.0, state.attributes.get('hysteresis')) - self.assertEqual('upper', state.attributes.get('type')) + assert 'sensor.test_monitored' == \ + state.attributes.get('entity_id') + assert 16 == state.attributes.get('sensor_value') + assert 'above' == state.attributes.get('position') + assert float(config['binary_sensor']['upper']) == \ + state.attributes.get('upper') + assert 0.0 == state.attributes.get('hysteresis') + assert 'upper' == state.attributes.get('type') assert state.state == 'on' @@ -79,11 +79,11 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('above', state.attributes.get('position')) - self.assertEqual(float(config['binary_sensor']['lower']), - state.attributes.get('lower')) - self.assertEqual(0.0, state.attributes.get('hysteresis')) - self.assertEqual('lower', state.attributes.get('type')) + assert 'above' == state.attributes.get('position') + assert float(config['binary_sensor']['lower']) == \ + state.attributes.get('lower') + assert 0.0 == state.attributes.get('hysteresis') + assert 'lower' == state.attributes.get('type') assert state.state == 'off' @@ -112,11 +112,11 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('above', state.attributes.get('position')) - self.assertEqual(float(config['binary_sensor']['upper']), - state.attributes.get('upper')) - self.assertEqual(2.5, state.attributes.get('hysteresis')) - self.assertEqual('upper', state.attributes.get('type')) + assert 'above' == state.attributes.get('position') + assert float(config['binary_sensor']['upper']) == \ + state.attributes.get('upper') + assert 2.5 == state.attributes.get('hysteresis') + assert 'upper' == state.attributes.get('type') assert state.state == 'on' @@ -167,16 +167,16 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('sensor.test_monitored', - state.attributes.get('entity_id')) - self.assertEqual(16, state.attributes.get('sensor_value')) - self.assertEqual('in_range', state.attributes.get('position')) - self.assertEqual(float(config['binary_sensor']['lower']), - state.attributes.get('lower')) - self.assertEqual(float(config['binary_sensor']['upper']), - state.attributes.get('upper')) - self.assertEqual(0.0, state.attributes.get('hysteresis')) - self.assertEqual('range', state.attributes.get('type')) + assert 'sensor.test_monitored' == \ + state.attributes.get('entity_id') + assert 16 == state.attributes.get('sensor_value') + assert 'in_range' == state.attributes.get('position') + assert float(config['binary_sensor']['lower']) == \ + state.attributes.get('lower') + assert float(config['binary_sensor']['upper']) == \ + state.attributes.get('upper') + assert 0.0 == state.attributes.get('hysteresis') + assert 'range' == state.attributes.get('type') assert state.state == 'on' @@ -185,7 +185,7 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('below', state.attributes.get('position')) + assert 'below' == state.attributes.get('position') assert state.state == 'off' self.hass.states.set('sensor.test_monitored', 21) @@ -193,7 +193,7 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('above', state.attributes.get('position')) + assert 'above' == state.attributes.get('position') assert state.state == 'off' def test_sensor_in_range_with_hysteresis(self): @@ -216,17 +216,17 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('sensor.test_monitored', - state.attributes.get('entity_id')) - self.assertEqual(16, state.attributes.get('sensor_value')) - self.assertEqual('in_range', state.attributes.get('position')) - self.assertEqual(float(config['binary_sensor']['lower']), - state.attributes.get('lower')) - self.assertEqual(float(config['binary_sensor']['upper']), - state.attributes.get('upper')) - self.assertEqual(float(config['binary_sensor']['hysteresis']), - state.attributes.get('hysteresis')) - self.assertEqual('range', state.attributes.get('type')) + assert 'sensor.test_monitored' == \ + state.attributes.get('entity_id') + assert 16 == state.attributes.get('sensor_value') + assert 'in_range' == state.attributes.get('position') + assert float(config['binary_sensor']['lower']) == \ + state.attributes.get('lower') + assert float(config['binary_sensor']['upper']) == \ + state.attributes.get('upper') + assert float(config['binary_sensor']['hysteresis']) == \ + state.attributes.get('hysteresis') + assert 'range' == state.attributes.get('type') assert state.state == 'on' @@ -235,7 +235,7 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('in_range', state.attributes.get('position')) + assert 'in_range' == state.attributes.get('position') assert state.state == 'on' self.hass.states.set('sensor.test_monitored', 7) @@ -243,7 +243,7 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('below', state.attributes.get('position')) + assert 'below' == state.attributes.get('position') assert state.state == 'off' self.hass.states.set('sensor.test_monitored', 12) @@ -251,7 +251,7 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('below', state.attributes.get('position')) + assert 'below' == state.attributes.get('position') assert state.state == 'off' self.hass.states.set('sensor.test_monitored', 13) @@ -259,7 +259,7 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('in_range', state.attributes.get('position')) + assert 'in_range' == state.attributes.get('position') assert state.state == 'on' self.hass.states.set('sensor.test_monitored', 22) @@ -267,7 +267,7 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('in_range', state.attributes.get('position')) + assert 'in_range' == state.attributes.get('position') assert state.state == 'on' self.hass.states.set('sensor.test_monitored', 23) @@ -275,7 +275,7 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('above', state.attributes.get('position')) + assert 'above' == state.attributes.get('position') assert state.state == 'off' self.hass.states.set('sensor.test_monitored', 18) @@ -283,7 +283,7 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('above', state.attributes.get('position')) + assert 'above' == state.attributes.get('position') assert state.state == 'off' self.hass.states.set('sensor.test_monitored', 17) @@ -291,7 +291,7 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('in_range', state.attributes.get('position')) + assert 'in_range' == state.attributes.get('position') assert state.state == 'on' def test_sensor_in_range_unknown_state(self): @@ -313,16 +313,16 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('sensor.test_monitored', - state.attributes.get('entity_id')) - self.assertEqual(16, state.attributes.get('sensor_value')) - self.assertEqual('in_range', state.attributes.get('position')) - self.assertEqual(float(config['binary_sensor']['lower']), - state.attributes.get('lower')) - self.assertEqual(float(config['binary_sensor']['upper']), - state.attributes.get('upper')) - self.assertEqual(0.0, state.attributes.get('hysteresis')) - self.assertEqual('range', state.attributes.get('type')) + assert 'sensor.test_monitored' == \ + state.attributes.get('entity_id') + assert 16 == state.attributes.get('sensor_value') + assert 'in_range' == state.attributes.get('position') + assert float(config['binary_sensor']['lower']) == \ + state.attributes.get('lower') + assert float(config['binary_sensor']['upper']) == \ + state.attributes.get('upper') + assert 0.0 == state.attributes.get('hysteresis') + assert 'range' == state.attributes.get('type') assert state.state == 'on' @@ -331,7 +331,7 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('unknown', state.attributes.get('position')) + assert 'unknown' == state.attributes.get('position') assert state.state == 'off' def test_sensor_lower_zero_threshold(self): @@ -351,9 +351,9 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('lower', state.attributes.get('type')) - self.assertEqual(float(config['binary_sensor']['lower']), - state.attributes.get('lower')) + assert 'lower' == state.attributes.get('type') + assert float(config['binary_sensor']['lower']) == \ + state.attributes.get('lower') assert state.state == 'off' @@ -381,9 +381,9 @@ class TestThresholdSensor(unittest.TestCase): state = self.hass.states.get('binary_sensor.threshold') - self.assertEqual('upper', state.attributes.get('type')) - self.assertEqual(float(config['binary_sensor']['upper']), - state.attributes.get('upper')) + assert 'upper' == state.attributes.get('type') + assert float(config['binary_sensor']['upper']) == \ + state.attributes.get('upper') assert state.state == 'off' diff --git a/tests/components/binary_sensor/test_vultr.py b/tests/components/binary_sensor/test_vultr.py index f356149dd..ee19cf941 100644 --- a/tests/components/binary_sensor/test_vultr.py +++ b/tests/components/binary_sensor/test_vultr.py @@ -74,53 +74,53 @@ class TestVultrBinarySensorSetup(unittest.TestCase): self.add_entities, None) - self.assertEqual(len(self.DEVICES), 3) + assert len(self.DEVICES) == 3 for device in self.DEVICES: # Test pre data retrieval if device.subscription == '555555': - self.assertEqual('Vultr {}', device.name) + assert 'Vultr {}' == device.name device.update() device_attrs = device.device_state_attributes if device.subscription == '555555': - self.assertEqual('Vultr Another Server', device.name) + assert 'Vultr Another Server' == device.name if device.name == 'A Server': - self.assertEqual(True, device.is_on) - self.assertEqual('power', device.device_class) - self.assertEqual('on', device.state) - self.assertEqual('mdi:server', device.icon) - self.assertEqual('1000', - device_attrs[ATTR_ALLOWED_BANDWIDTH]) - self.assertEqual('yes', - device_attrs[ATTR_AUTO_BACKUPS]) - self.assertEqual('123.123.123.123', - device_attrs[ATTR_IPV4_ADDRESS]) - self.assertEqual('10.05', - device_attrs[ATTR_COST_PER_MONTH]) - self.assertEqual('2013-12-19 14:45:41', - device_attrs[ATTR_CREATED_AT]) - self.assertEqual('576965', - device_attrs[ATTR_SUBSCRIPTION_ID]) + assert device.is_on is True + assert 'power' == device.device_class + assert 'on' == device.state + assert 'mdi:server' == device.icon + assert '1000' == \ + device_attrs[ATTR_ALLOWED_BANDWIDTH] + assert 'yes' == \ + device_attrs[ATTR_AUTO_BACKUPS] + assert '123.123.123.123' == \ + device_attrs[ATTR_IPV4_ADDRESS] + assert '10.05' == \ + device_attrs[ATTR_COST_PER_MONTH] + assert '2013-12-19 14:45:41' == \ + device_attrs[ATTR_CREATED_AT] + assert '576965' == \ + device_attrs[ATTR_SUBSCRIPTION_ID] elif device.name == 'Failed Server': - self.assertEqual(False, device.is_on) - self.assertEqual('off', device.state) - self.assertEqual('mdi:server-off', device.icon) - self.assertEqual('1000', - device_attrs[ATTR_ALLOWED_BANDWIDTH]) - self.assertEqual('no', - device_attrs[ATTR_AUTO_BACKUPS]) - self.assertEqual('192.168.100.50', - device_attrs[ATTR_IPV4_ADDRESS]) - self.assertEqual('73.25', - device_attrs[ATTR_COST_PER_MONTH]) - self.assertEqual('2014-10-13 14:45:41', - device_attrs[ATTR_CREATED_AT]) - self.assertEqual('123456', - device_attrs[ATTR_SUBSCRIPTION_ID]) + assert device.is_on is False + assert 'off' == device.state + assert 'mdi:server-off' == device.icon + assert '1000' == \ + device_attrs[ATTR_ALLOWED_BANDWIDTH] + assert 'no' == \ + device_attrs[ATTR_AUTO_BACKUPS] + assert '192.168.100.50' == \ + device_attrs[ATTR_IPV4_ADDRESS] + assert '73.25' == \ + device_attrs[ATTR_COST_PER_MONTH] + assert '2014-10-13 14:45:41' == \ + device_attrs[ATTR_CREATED_AT] + assert '123456' == \ + device_attrs[ATTR_SUBSCRIPTION_ID] def test_invalid_sensor_config(self): """Test config type failures.""" @@ -150,7 +150,7 @@ class TestVultrBinarySensorSetup(unittest.TestCase): self.add_entities, None) - self.assertFalse(no_subs_setup) + assert not no_subs_setup bad_conf = { CONF_NAME: "Missing Server", @@ -162,4 +162,4 @@ class TestVultrBinarySensorSetup(unittest.TestCase): self.add_entities, None) - self.assertFalse(wrong_subs_setup) + assert not wrong_subs_setup diff --git a/tests/components/calendar/test_caldav.py b/tests/components/calendar/test_caldav.py index c5dadbc56..45de0052c 100644 --- a/tests/components/calendar/test_caldav.py +++ b/tests/components/calendar/test_caldav.py @@ -178,10 +178,10 @@ class TestComponentsWebDavCalendar(unittest.TestCase): assert len(devices) == 2 assert devices[0].name == "First" assert devices[0].dev_id == "First" - self.assertFalse(devices[0].data.include_all_day) + assert not devices[0].data.include_all_day assert devices[1].name == "Second" assert devices[1].dev_id == "Second" - self.assertFalse(devices[1].data.include_all_day) + assert not devices[1].data.include_all_day caldav.setup_platform(self.hass, { @@ -226,7 +226,7 @@ class TestComponentsWebDavCalendar(unittest.TestCase): assert len(devices) == 1 assert devices[0].name == "HomeOffice" assert devices[0].dev_id == "Second HomeOffice" - self.assertTrue(devices[0].data.include_all_day) + assert devices[0].data.include_all_day caldav.setup_platform(self.hass, { @@ -247,9 +247,9 @@ class TestComponentsWebDavCalendar(unittest.TestCase): DEVICE_DATA, self.calendar) - self.assertEqual(cal.name, DEVICE_DATA["name"]) - self.assertEqual(cal.state, STATE_ON) - self.assertEqual(cal.device_state_attributes, { + assert cal.name == DEVICE_DATA["name"] + assert cal.state == STATE_ON + assert cal.device_state_attributes == { "message": "This is a normal event", "all_day": False, "offset_reached": False, @@ -257,7 +257,7 @@ class TestComponentsWebDavCalendar(unittest.TestCase): "end_time": "2017-11-27 18:00:00", "location": "Hamburg", "description": "Surprisingly rainy", - }) + } @patch('homeassistant.util.dt.now', return_value=_local_datetime(17, 30)) def test_just_ended_event(self, mock_now): @@ -266,9 +266,9 @@ class TestComponentsWebDavCalendar(unittest.TestCase): DEVICE_DATA, self.calendar) - self.assertEqual(cal.name, DEVICE_DATA["name"]) - self.assertEqual(cal.state, STATE_ON) - self.assertEqual(cal.device_state_attributes, { + assert cal.name == DEVICE_DATA["name"] + assert cal.state == STATE_ON + assert cal.device_state_attributes == { "message": "This is a normal event", "all_day": False, "offset_reached": False, @@ -276,7 +276,7 @@ class TestComponentsWebDavCalendar(unittest.TestCase): "end_time": "2017-11-27 18:00:00", "location": "Hamburg", "description": "Surprisingly rainy", - }) + } @patch('homeassistant.util.dt.now', return_value=_local_datetime(17, 00)) def test_ongoing_event_different_tz(self, mock_now): @@ -285,9 +285,9 @@ class TestComponentsWebDavCalendar(unittest.TestCase): DEVICE_DATA, self.calendar) - self.assertEqual(cal.name, DEVICE_DATA["name"]) - self.assertEqual(cal.state, STATE_ON) - self.assertEqual(cal.device_state_attributes, { + assert cal.name == DEVICE_DATA["name"] + assert cal.state == STATE_ON + assert cal.device_state_attributes == { "message": "Enjoy the sun", "all_day": False, "offset_reached": False, @@ -295,7 +295,7 @@ class TestComponentsWebDavCalendar(unittest.TestCase): "description": "Sunny day", "end_time": "2017-11-27 17:30:00", "location": "San Francisco", - }) + } @patch('homeassistant.util.dt.now', return_value=_local_datetime(8, 30)) def test_ongoing_event_with_offset(self, mock_now): @@ -304,8 +304,8 @@ class TestComponentsWebDavCalendar(unittest.TestCase): DEVICE_DATA, self.calendar) - self.assertEqual(cal.state, STATE_OFF) - self.assertEqual(cal.device_state_attributes, { + assert cal.state == STATE_OFF + assert cal.device_state_attributes == { "message": "This is an offset event", "all_day": False, "offset_reached": True, @@ -313,7 +313,7 @@ class TestComponentsWebDavCalendar(unittest.TestCase): "end_time": "2017-11-27 11:00:00", "location": "Hamburg", "description": "Surprisingly shiny", - }) + } @patch('homeassistant.util.dt.now', return_value=_local_datetime(12, 00)) def test_matching_filter(self, mock_now): @@ -324,9 +324,9 @@ class TestComponentsWebDavCalendar(unittest.TestCase): False, "This is a normal event") - self.assertEqual(cal.state, STATE_OFF) - self.assertFalse(cal.offset_reached()) - self.assertEqual(cal.device_state_attributes, { + assert cal.state == STATE_OFF + assert not cal.offset_reached() + assert cal.device_state_attributes == { "message": "This is a normal event", "all_day": False, "offset_reached": False, @@ -334,7 +334,7 @@ class TestComponentsWebDavCalendar(unittest.TestCase): "end_time": "2017-11-27 18:00:00", "location": "Hamburg", "description": "Surprisingly rainy", - }) + } @patch('homeassistant.util.dt.now', return_value=_local_datetime(12, 00)) def test_matching_filter_real_regexp(self, mock_now): @@ -345,9 +345,9 @@ class TestComponentsWebDavCalendar(unittest.TestCase): False, "^This.*event") - self.assertEqual(cal.state, STATE_OFF) - self.assertFalse(cal.offset_reached()) - self.assertEqual(cal.device_state_attributes, { + assert cal.state == STATE_OFF + assert not cal.offset_reached() + assert cal.device_state_attributes == { "message": "This is a normal event", "all_day": False, "offset_reached": False, @@ -355,7 +355,7 @@ class TestComponentsWebDavCalendar(unittest.TestCase): "end_time": "2017-11-27 18:00:00", "location": "Hamburg", "description": "Surprisingly rainy", - }) + } @patch('homeassistant.util.dt.now', return_value=_local_datetime(20, 00)) def test_filter_matching_past_event(self, mock_now): @@ -366,7 +366,7 @@ class TestComponentsWebDavCalendar(unittest.TestCase): False, "This is a normal event") - self.assertEqual(cal.data.event, None) + assert cal.data.event is None @patch('homeassistant.util.dt.now', return_value=_local_datetime(12, 00)) def test_no_result_with_filtering(self, mock_now): @@ -377,7 +377,7 @@ class TestComponentsWebDavCalendar(unittest.TestCase): False, "This is a non-existing event") - self.assertEqual(cal.data.event, None) + assert cal.data.event is None @patch('homeassistant.util.dt.now', return_value=_local_datetime(17, 30)) def test_all_day_event_returned(self, mock_now): @@ -387,9 +387,9 @@ class TestComponentsWebDavCalendar(unittest.TestCase): self.calendar, True) - self.assertEqual(cal.name, DEVICE_DATA["name"]) - self.assertEqual(cal.state, STATE_ON) - self.assertEqual(cal.device_state_attributes, { + assert cal.name == DEVICE_DATA["name"] + assert cal.state == STATE_ON + assert cal.device_state_attributes == { "message": "This is an all day event", "all_day": True, "offset_reached": False, @@ -397,4 +397,4 @@ class TestComponentsWebDavCalendar(unittest.TestCase): "end_time": "2017-11-28 00:00:00", "location": "Hamburg", "description": "What a beautiful day", - }) + } diff --git a/tests/components/calendar/test_google.py b/tests/components/calendar/test_google.py index e07f7a630..ec4089677 100644 --- a/tests/components/calendar/test_google.py +++ b/tests/components/calendar/test_google.py @@ -87,13 +87,13 @@ class TestComponentsGoogleCalendar(unittest.TestCase): cal = calendar.GoogleCalendarEventDevice(self.hass, None, '', {'name': device_name}) - self.assertEqual(cal.name, device_name) + assert cal.name == device_name - self.assertEqual(cal.state, STATE_OFF) + assert cal.state == STATE_OFF - self.assertFalse(cal.offset_reached()) + assert not cal.offset_reached() - self.assertEqual(cal.device_state_attributes, { + assert cal.device_state_attributes == { 'message': event['summary'], 'all_day': True, 'offset_reached': False, @@ -101,7 +101,7 @@ class TestComponentsGoogleCalendar(unittest.TestCase): 'end_time': '{} 00:00:00'.format(event['end']['date']), 'location': event['location'], 'description': event['description'], - }) + } @patch('homeassistant.components.calendar.google.GoogleCalendarData') def test_future_event(self, mock_next_event): @@ -146,13 +146,13 @@ class TestComponentsGoogleCalendar(unittest.TestCase): cal = calendar.GoogleCalendarEventDevice(self.hass, None, device_id, {'name': device_name}) - self.assertEqual(cal.name, device_name) + assert cal.name == device_name - self.assertEqual(cal.state, STATE_OFF) + assert cal.state == STATE_OFF - self.assertFalse(cal.offset_reached()) + assert not cal.offset_reached() - self.assertEqual(cal.device_state_attributes, { + assert cal.device_state_attributes == { 'message': event['summary'], 'all_day': False, 'offset_reached': False, @@ -162,7 +162,7 @@ class TestComponentsGoogleCalendar(unittest.TestCase): .strftime(DATE_STR_FORMAT), 'location': '', 'description': '', - }) + } @patch('homeassistant.components.calendar.google.GoogleCalendarData') def test_in_progress_event(self, mock_next_event): @@ -208,13 +208,13 @@ class TestComponentsGoogleCalendar(unittest.TestCase): cal = calendar.GoogleCalendarEventDevice(self.hass, None, device_id, {'name': device_name}) - self.assertEqual(cal.name, device_name) + assert cal.name == device_name - self.assertEqual(cal.state, STATE_ON) + assert cal.state == STATE_ON - self.assertFalse(cal.offset_reached()) + assert not cal.offset_reached() - self.assertEqual(cal.device_state_attributes, { + assert cal.device_state_attributes == { 'message': event['summary'], 'all_day': False, 'offset_reached': False, @@ -224,7 +224,7 @@ class TestComponentsGoogleCalendar(unittest.TestCase): .strftime(DATE_STR_FORMAT), 'location': '', 'description': '', - }) + } @patch('homeassistant.components.calendar.google.GoogleCalendarData') def test_offset_in_progress_event(self, mock_next_event): @@ -271,13 +271,13 @@ class TestComponentsGoogleCalendar(unittest.TestCase): cal = calendar.GoogleCalendarEventDevice(self.hass, None, device_id, {'name': device_name}) - self.assertEqual(cal.name, device_name) + assert cal.name == device_name - self.assertEqual(cal.state, STATE_OFF) + assert cal.state == STATE_OFF - self.assertTrue(cal.offset_reached()) + assert cal.offset_reached() - self.assertEqual(cal.device_state_attributes, { + assert cal.device_state_attributes == { 'message': event_summary, 'all_day': False, 'offset_reached': True, @@ -287,7 +287,7 @@ class TestComponentsGoogleCalendar(unittest.TestCase): .strftime(DATE_STR_FORMAT), 'location': '', 'description': '', - }) + } @pytest.mark.skip @patch('homeassistant.components.calendar.google.GoogleCalendarData') @@ -340,13 +340,13 @@ class TestComponentsGoogleCalendar(unittest.TestCase): cal = calendar.GoogleCalendarEventDevice(self.hass, None, device_id, {'name': device_name}) - self.assertEqual(cal.name, device_name) + assert cal.name == device_name - self.assertEqual(cal.state, STATE_OFF) + assert cal.state == STATE_OFF - self.assertTrue(cal.offset_reached()) + assert cal.offset_reached() - self.assertEqual(cal.device_state_attributes, { + assert cal.device_state_attributes == { 'message': event_summary, 'all_day': True, 'offset_reached': True, @@ -354,7 +354,7 @@ class TestComponentsGoogleCalendar(unittest.TestCase): 'end_time': '{} 06:00:00'.format(event['end']['date']), 'location': event['location'], 'description': event['description'], - }) + } @patch('homeassistant.components.calendar.google.GoogleCalendarData') def test_all_day_offset_event(self, mock_next_event): @@ -407,13 +407,13 @@ class TestComponentsGoogleCalendar(unittest.TestCase): cal = calendar.GoogleCalendarEventDevice(self.hass, None, device_id, {'name': device_name}) - self.assertEqual(cal.name, device_name) + assert cal.name == device_name - self.assertEqual(cal.state, STATE_OFF) + assert cal.state == STATE_OFF - self.assertFalse(cal.offset_reached()) + assert not cal.offset_reached() - self.assertEqual(cal.device_state_attributes, { + assert cal.device_state_attributes == { 'message': event_summary, 'all_day': True, 'offset_reached': False, @@ -421,7 +421,7 @@ class TestComponentsGoogleCalendar(unittest.TestCase): 'end_time': '{} 00:00:00'.format(event['end']['date']), 'location': event['location'], 'description': event['description'], - }) + } @MockDependency("httplib2") def test_update_false(self, mock_httplib2): @@ -434,4 +434,4 @@ class TestComponentsGoogleCalendar(unittest.TestCase): {'name': "test"}) result = cal.data.update() - self.assertFalse(result) + assert not result diff --git a/tests/components/camera/test_uvc.py b/tests/components/camera/test_uvc.py index 328ba5096..b41cb9f86 100644 --- a/tests/components/camera/test_uvc.py +++ b/tests/components/camera/test_uvc.py @@ -11,6 +11,7 @@ from homeassistant.exceptions import PlatformNotReady from homeassistant.setup import setup_component from homeassistant.components.camera import uvc from tests.common import get_test_home_assistant +import pytest class TestUVCSetup(unittest.TestCase): @@ -53,10 +54,8 @@ class TestUVCSetup(unittest.TestCase): assert setup_component(self.hass, 'camera', {'camera': config}) - self.assertEqual(mock_remote.call_count, 1) - self.assertEqual( - mock_remote.call_args, mock.call('foo', 123, 'secret') - ) + assert mock_remote.call_count == 1 + assert mock_remote.call_args == mock.call('foo', 123, 'secret') mock_uvc.assert_has_calls([ mock.call(mock_remote.return_value, 'id1', 'Front', 'bar'), mock.call(mock_remote.return_value, 'id2', 'Back', 'bar'), @@ -81,10 +80,8 @@ class TestUVCSetup(unittest.TestCase): assert setup_component(self.hass, 'camera', {'camera': config}) - self.assertEqual(mock_remote.call_count, 1) - self.assertEqual( - mock_remote.call_args, mock.call('foo', 7080, 'secret') - ) + assert mock_remote.call_count == 1 + assert mock_remote.call_args == mock.call('foo', 7080, 'secret') mock_uvc.assert_has_calls([ mock.call(mock_remote.return_value, 'id1', 'Front', 'ubnt'), mock.call(mock_remote.return_value, 'id2', 'Back', 'ubnt'), @@ -109,10 +106,8 @@ class TestUVCSetup(unittest.TestCase): assert setup_component(self.hass, 'camera', {'camera': config}) - self.assertEqual(mock_remote.call_count, 1) - self.assertEqual( - mock_remote.call_args, mock.call('foo', 7080, 'secret') - ) + assert mock_remote.call_count == 1 + assert mock_remote.call_args == mock.call('foo', 7080, 'secret') mock_uvc.assert_has_calls([ mock.call(mock_remote.return_value, 'one', 'Front', 'ubnt'), mock.call(mock_remote.return_value, 'two', 'Back', 'ubnt'), @@ -151,13 +146,13 @@ class TestUVCSetup(unittest.TestCase): def test_setup_nvr_error_during_indexing_nvrerror(self): """Test for error: nvr.NvrError.""" self.setup_nvr_errors_during_indexing(nvr.NvrError) - self.assertRaises(PlatformNotReady) + pytest.raises(PlatformNotReady) def test_setup_nvr_error_during_indexing_connectionerror(self): """Test for error: requests.exceptions.ConnectionError.""" self.setup_nvr_errors_during_indexing( requests.exceptions.ConnectionError) - self.assertRaises(PlatformNotReady) + pytest.raises(PlatformNotReady) @mock.patch.object(uvc, 'UnifiVideoCamera') @mock.patch('uvcclient.nvr.UVCRemote.__init__') @@ -182,13 +177,13 @@ class TestUVCSetup(unittest.TestCase): def test_setup_nvr_error_during_initialization_nvrerror(self): """Test for error: nvr.NvrError.""" self.setup_nvr_errors_during_initialization(nvr.NvrError) - self.assertRaises(PlatformNotReady) + pytest.raises(PlatformNotReady) def test_setup_nvr_error_during_initialization_connectionerror(self): """Test for error: requests.exceptions.ConnectionError.""" self.setup_nvr_errors_during_initialization( requests.exceptions.ConnectionError) - self.assertRaises(PlatformNotReady) + pytest.raises(PlatformNotReady) class TestUVC(unittest.TestCase): @@ -215,22 +210,20 @@ class TestUVC(unittest.TestCase): def test_properties(self): """Test the properties.""" - self.assertEqual(self.name, self.uvc.name) - self.assertTrue(self.uvc.is_recording) - self.assertEqual('Ubiquiti', self.uvc.brand) - self.assertEqual('UVC Fake', self.uvc.model) + assert self.name == self.uvc.name + assert self.uvc.is_recording + assert 'Ubiquiti' == self.uvc.brand + assert 'UVC Fake' == self.uvc.model @mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClientV320') def test_login(self, mock_camera, mock_store): """Test the login.""" self.uvc._login() - self.assertEqual(mock_camera.call_count, 1) - self.assertEqual( - mock_camera.call_args, mock.call('host-a', 'admin', 'seekret') - ) - self.assertEqual(mock_camera.return_value.login.call_count, 1) - self.assertEqual(mock_camera.return_value.login.call_args, mock.call()) + assert mock_camera.call_count == 1 + assert mock_camera.call_args == mock.call('host-a', 'admin', 'seekret') + assert mock_camera.return_value.login.call_count == 1 + assert mock_camera.return_value.login.call_args == mock.call() @mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClient') @@ -238,12 +231,10 @@ class TestUVC(unittest.TestCase): """Test login with v3.1.x server.""" self.nvr.server_version = (3, 1, 3) self.uvc._login() - self.assertEqual(mock_camera.call_count, 1) - self.assertEqual( - mock_camera.call_args, mock.call('host-a', 'admin', 'seekret') - ) - self.assertEqual(mock_camera.return_value.login.call_count, 1) - self.assertEqual(mock_camera.return_value.login.call_args, mock.call()) + assert mock_camera.call_count == 1 + assert mock_camera.call_args == mock.call('host-a', 'admin', 'seekret') + assert mock_camera.return_value.login.call_count == 1 + assert mock_camera.return_value.login.call_args == mock.call() @mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClientV320') @@ -262,45 +253,43 @@ class TestUVC(unittest.TestCase): mock_store.return_value.get_camera_password.return_value = None mock_camera.return_value.login.side_effect = mock_login self.uvc._login() - self.assertEqual(2, mock_camera.call_count) - self.assertEqual('host-b', self.uvc._connect_addr) + assert 2 == mock_camera.call_count + assert 'host-b' == self.uvc._connect_addr mock_camera.reset_mock() self.uvc._login() - self.assertEqual(mock_camera.call_count, 1) - self.assertEqual( - mock_camera.call_args, mock.call('host-b', 'admin', 'seekret') - ) - self.assertEqual(mock_camera.return_value.login.call_count, 1) - self.assertEqual(mock_camera.return_value.login.call_args, mock.call()) + assert mock_camera.call_count == 1 + assert mock_camera.call_args == mock.call('host-b', 'admin', 'seekret') + assert mock_camera.return_value.login.call_count == 1 + assert mock_camera.return_value.login.call_args == mock.call() @mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClientV320') def test_login_fails_both_properly(self, mock_camera, mock_store): """Test if login fails properly.""" mock_camera.return_value.login.side_effect = socket.error - self.assertEqual(None, self.uvc._login()) - self.assertEqual(None, self.uvc._connect_addr) + assert self.uvc._login() is None + assert self.uvc._connect_addr is None def test_camera_image_tries_login_bails_on_failure(self): """Test retrieving failure.""" with mock.patch.object(self.uvc, '_login') as mock_login: mock_login.return_value = False - self.assertEqual(None, self.uvc.camera_image()) - self.assertEqual(mock_login.call_count, 1) - self.assertEqual(mock_login.call_args, mock.call()) + assert self.uvc.camera_image() is None + assert mock_login.call_count == 1 + assert mock_login.call_args == mock.call() def test_camera_image_logged_in(self): """Test the login state.""" self.uvc._camera = mock.MagicMock() - self.assertEqual(self.uvc._camera.get_snapshot.return_value, - self.uvc.camera_image()) + assert self.uvc._camera.get_snapshot.return_value == \ + self.uvc.camera_image() def test_camera_image_error(self): """Test the camera image error.""" self.uvc._camera = mock.MagicMock() self.uvc._camera.get_snapshot.side_effect = camera.CameraConnectError - self.assertEqual(None, self.uvc.camera_image()) + assert self.uvc.camera_image() is None def test_camera_image_reauths(self): """Test the re-authentication.""" @@ -318,16 +307,17 @@ class TestUVC(unittest.TestCase): self.uvc._camera = mock.MagicMock() self.uvc._camera.get_snapshot.side_effect = mock_snapshot with mock.patch.object(self.uvc, '_login') as mock_login: - self.assertEqual('image', self.uvc.camera_image()) - self.assertEqual(mock_login.call_count, 1) - self.assertEqual(mock_login.call_args, mock.call()) - self.assertEqual([], responses) + assert 'image' == self.uvc.camera_image() + assert mock_login.call_count == 1 + assert mock_login.call_args == mock.call() + assert [] == responses def test_camera_image_reauths_only_once(self): """Test if the re-authentication only happens once.""" self.uvc._camera = mock.MagicMock() self.uvc._camera.get_snapshot.side_effect = camera.CameraAuthError with mock.patch.object(self.uvc, '_login') as mock_login: - self.assertRaises(camera.CameraAuthError, self.uvc.camera_image) - self.assertEqual(mock_login.call_count, 1) - self.assertEqual(mock_login.call_args, mock.call()) + with pytest.raises(camera.CameraAuthError): + self.uvc.camera_image() + assert mock_login.call_count == 1 + assert mock_login.call_args == mock.call() diff --git a/tests/components/climate/test_demo.py b/tests/components/climate/test_demo.py index 4990a8a69..462939af2 100644 --- a/tests/components/climate/test_demo.py +++ b/tests/components/climate/test_demo.py @@ -23,10 +23,10 @@ class TestDemoClimate(unittest.TestCase): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.units = METRIC_SYSTEM - self.assertTrue(setup_component(self.hass, climate.DOMAIN, { + assert setup_component(self.hass, climate.DOMAIN, { 'climate': { 'platform': 'demo', - }})) + }}) def tearDown(self): # pylint: disable=invalid-name """Stop down everything that was started.""" @@ -35,132 +35,132 @@ class TestDemoClimate(unittest.TestCase): def test_setup_params(self): """Test the initial parameters.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(21, state.attributes.get('temperature')) - self.assertEqual('on', state.attributes.get('away_mode')) - self.assertEqual(22, state.attributes.get('current_temperature')) - self.assertEqual("On High", state.attributes.get('fan_mode')) - self.assertEqual(67, state.attributes.get('humidity')) - self.assertEqual(54, state.attributes.get('current_humidity')) - self.assertEqual("Off", state.attributes.get('swing_mode')) - self.assertEqual("cool", state.attributes.get('operation_mode')) - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 21 == state.attributes.get('temperature') + assert 'on' == state.attributes.get('away_mode') + assert 22 == state.attributes.get('current_temperature') + assert "On High" == state.attributes.get('fan_mode') + assert 67 == state.attributes.get('humidity') + assert 54 == state.attributes.get('current_humidity') + assert "Off" == state.attributes.get('swing_mode') + assert "cool" == state.attributes.get('operation_mode') + assert 'off' == state.attributes.get('aux_heat') def test_default_setup_params(self): """Test the setup with default parameters.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(7, state.attributes.get('min_temp')) - self.assertEqual(35, state.attributes.get('max_temp')) - self.assertEqual(30, state.attributes.get('min_humidity')) - self.assertEqual(99, state.attributes.get('max_humidity')) + assert 7 == state.attributes.get('min_temp') + assert 35 == state.attributes.get('max_temp') + assert 30 == state.attributes.get('min_humidity') + assert 99 == state.attributes.get('max_humidity') def test_set_only_target_temp_bad_attr(self): """Test setting the target temperature without required attribute.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(21, state.attributes.get('temperature')) + assert 21 == state.attributes.get('temperature') common.set_temperature(self.hass, None, ENTITY_CLIMATE) self.hass.block_till_done() - self.assertEqual(21, state.attributes.get('temperature')) + assert 21 == state.attributes.get('temperature') def test_set_only_target_temp(self): """Test the setting of the target temperature.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(21, state.attributes.get('temperature')) + assert 21 == state.attributes.get('temperature') common.set_temperature(self.hass, 30, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(30.0, state.attributes.get('temperature')) + assert 30.0 == state.attributes.get('temperature') def test_set_only_target_temp_with_convert(self): """Test the setting of the target temperature.""" state = self.hass.states.get(ENTITY_HEATPUMP) - self.assertEqual(20, state.attributes.get('temperature')) + assert 20 == state.attributes.get('temperature') common.set_temperature(self.hass, 21, ENTITY_HEATPUMP) self.hass.block_till_done() state = self.hass.states.get(ENTITY_HEATPUMP) - self.assertEqual(21.0, state.attributes.get('temperature')) + assert 21.0 == state.attributes.get('temperature') def test_set_target_temp_range(self): """Test the setting of the target temperature with range.""" state = self.hass.states.get(ENTITY_ECOBEE) - self.assertEqual(None, state.attributes.get('temperature')) - self.assertEqual(21.0, state.attributes.get('target_temp_low')) - self.assertEqual(24.0, state.attributes.get('target_temp_high')) + assert state.attributes.get('temperature') is None + assert 21.0 == state.attributes.get('target_temp_low') + assert 24.0 == state.attributes.get('target_temp_high') common.set_temperature(self.hass, target_temp_high=25, target_temp_low=20, entity_id=ENTITY_ECOBEE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ECOBEE) - self.assertEqual(None, state.attributes.get('temperature')) - self.assertEqual(20.0, state.attributes.get('target_temp_low')) - self.assertEqual(25.0, state.attributes.get('target_temp_high')) + assert state.attributes.get('temperature') is None + assert 20.0 == state.attributes.get('target_temp_low') + assert 25.0 == state.attributes.get('target_temp_high') def test_set_target_temp_range_bad_attr(self): """Test setting the target temperature range without attribute.""" state = self.hass.states.get(ENTITY_ECOBEE) - self.assertEqual(None, state.attributes.get('temperature')) - self.assertEqual(21.0, state.attributes.get('target_temp_low')) - self.assertEqual(24.0, state.attributes.get('target_temp_high')) + assert state.attributes.get('temperature') is None + assert 21.0 == state.attributes.get('target_temp_low') + assert 24.0 == state.attributes.get('target_temp_high') common.set_temperature(self.hass, temperature=None, entity_id=ENTITY_ECOBEE, target_temp_low=None, target_temp_high=None) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ECOBEE) - self.assertEqual(None, state.attributes.get('temperature')) - self.assertEqual(21.0, state.attributes.get('target_temp_low')) - self.assertEqual(24.0, state.attributes.get('target_temp_high')) + assert state.attributes.get('temperature') is None + assert 21.0 == state.attributes.get('target_temp_low') + assert 24.0 == state.attributes.get('target_temp_high') def test_set_target_humidity_bad_attr(self): """Test setting the target humidity without required attribute.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(67, state.attributes.get('humidity')) + assert 67 == state.attributes.get('humidity') common.set_humidity(self.hass, None, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(67, state.attributes.get('humidity')) + assert 67 == state.attributes.get('humidity') def test_set_target_humidity(self): """Test the setting of the target humidity.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(67, state.attributes.get('humidity')) + assert 67 == state.attributes.get('humidity') common.set_humidity(self.hass, 64, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(64.0, state.attributes.get('humidity')) + assert 64.0 == state.attributes.get('humidity') def test_set_fan_mode_bad_attr(self): """Test setting fan mode without required attribute.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("On High", state.attributes.get('fan_mode')) + assert "On High" == state.attributes.get('fan_mode') common.set_fan_mode(self.hass, None, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("On High", state.attributes.get('fan_mode')) + assert "On High" == state.attributes.get('fan_mode') def test_set_fan_mode(self): """Test setting of new fan mode.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("On High", state.attributes.get('fan_mode')) + assert "On High" == state.attributes.get('fan_mode') common.set_fan_mode(self.hass, "On Low", ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("On Low", state.attributes.get('fan_mode')) + assert "On Low" == state.attributes.get('fan_mode') def test_set_swing_mode_bad_attr(self): """Test setting swing mode without required attribute.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("Off", state.attributes.get('swing_mode')) + assert "Off" == state.attributes.get('swing_mode') common.set_swing_mode(self.hass, None, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("Off", state.attributes.get('swing_mode')) + assert "Off" == state.attributes.get('swing_mode') def test_set_swing(self): """Test setting of new swing mode.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("Off", state.attributes.get('swing_mode')) + assert "Off" == state.attributes.get('swing_mode') common.set_swing_mode(self.hass, "Auto", ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("Auto", state.attributes.get('swing_mode')) + assert "Auto" == state.attributes.get('swing_mode') def test_set_operation_bad_attr_and_state(self): """Test setting operation mode without required attribute. @@ -168,103 +168,103 @@ class TestDemoClimate(unittest.TestCase): Also check the state. """ state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("cool", state.attributes.get('operation_mode')) - self.assertEqual("cool", state.state) + assert "cool" == state.attributes.get('operation_mode') + assert "cool" == state.state common.set_operation_mode(self.hass, None, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("cool", state.attributes.get('operation_mode')) - self.assertEqual("cool", state.state) + assert "cool" == state.attributes.get('operation_mode') + assert "cool" == state.state def test_set_operation(self): """Test setting of new operation mode.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("cool", state.attributes.get('operation_mode')) - self.assertEqual("cool", state.state) + assert "cool" == state.attributes.get('operation_mode') + assert "cool" == state.state common.set_operation_mode(self.hass, "heat", ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("heat", state.attributes.get('operation_mode')) - self.assertEqual("heat", state.state) + assert "heat" == state.attributes.get('operation_mode') + assert "heat" == state.state def test_set_away_mode_bad_attr(self): """Test setting the away mode without required attribute.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('away_mode')) + assert 'on' == state.attributes.get('away_mode') common.set_away_mode(self.hass, None, ENTITY_CLIMATE) self.hass.block_till_done() - self.assertEqual('on', state.attributes.get('away_mode')) + assert 'on' == state.attributes.get('away_mode') def test_set_away_mode_on(self): """Test setting the away mode on/true.""" common.set_away_mode(self.hass, True, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('away_mode')) + assert 'on' == state.attributes.get('away_mode') def test_set_away_mode_off(self): """Test setting the away mode off/false.""" common.set_away_mode(self.hass, False, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') def test_set_hold_mode_home(self): """Test setting the hold mode home.""" common.set_hold_mode(self.hass, 'home', ENTITY_ECOBEE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ECOBEE) - self.assertEqual('home', state.attributes.get('hold_mode')) + assert 'home' == state.attributes.get('hold_mode') def test_set_hold_mode_away(self): """Test setting the hold mode away.""" common.set_hold_mode(self.hass, 'away', ENTITY_ECOBEE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ECOBEE) - self.assertEqual('away', state.attributes.get('hold_mode')) + assert 'away' == state.attributes.get('hold_mode') def test_set_hold_mode_none(self): """Test setting the hold mode off/false.""" common.set_hold_mode(self.hass, 'off', ENTITY_ECOBEE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ECOBEE) - self.assertEqual('off', state.attributes.get('hold_mode')) + assert 'off' == state.attributes.get('hold_mode') def test_set_aux_heat_bad_attr(self): """Test setting the auxiliary heater without required attribute.""" state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 'off' == state.attributes.get('aux_heat') common.set_aux_heat(self.hass, None, ENTITY_CLIMATE) self.hass.block_till_done() - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 'off' == state.attributes.get('aux_heat') def test_set_aux_heat_on(self): """Test setting the axillary heater on/true.""" common.set_aux_heat(self.hass, True, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('aux_heat')) + assert 'on' == state.attributes.get('aux_heat') def test_set_aux_heat_off(self): """Test setting the auxiliary heater off/false.""" common.set_aux_heat(self.hass, False, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 'off' == state.attributes.get('aux_heat') def test_set_on_off(self): """Test on/off service.""" state = self.hass.states.get(ENTITY_ECOBEE) - self.assertEqual('auto', state.state) + assert 'auto' == state.state self.hass.services.call(climate.DOMAIN, climate.SERVICE_TURN_OFF, {climate.ATTR_ENTITY_ID: ENTITY_ECOBEE}) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ECOBEE) - self.assertEqual('off', state.state) + assert 'off' == state.state self.hass.services.call(climate.DOMAIN, climate.SERVICE_TURN_ON, {climate.ATTR_ENTITY_ID: ENTITY_ECOBEE}) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ECOBEE) - self.assertEqual('auto', state.state) + assert 'auto' == state.state diff --git a/tests/components/climate/test_dyson.py b/tests/components/climate/test_dyson.py index 6e8b63d64..e2cfffe64 100644 --- a/tests/components/climate/test_dyson.py +++ b/tests/components/climate/test_dyson.py @@ -123,7 +123,7 @@ class DysonTest(unittest.TestCase): dyson_parent.CONF_LANGUAGE: "US", } }) - self.assertEqual(len(self.hass.data[dyson.DYSON_DEVICES]), 2) + assert len(self.hass.data[dyson.DYSON_DEVICES]) == 2 self.hass.block_till_done() for m in mocked_devices.return_value: assert m.add_message_listener.called @@ -145,7 +145,7 @@ class DysonTest(unittest.TestCase): self.hass.data[dyson.DYSON_DEVICES] = devices add_devices = mock.MagicMock() dyson.setup_platform(self.hass, None, add_devices, discovery_info={}) - self.assertTrue(add_devices.called) + assert add_devices.called def test_setup_component_with_invalid_devices(self): """Test setup component with invalid devices.""" @@ -175,7 +175,7 @@ class DysonTest(unittest.TestCase): device = _get_device_heat_on() device.temp_unit = TEMP_CELSIUS entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertFalse(entity.should_poll) + assert not entity.should_poll # Without target temp. kwargs = {} @@ -223,7 +223,7 @@ class DysonTest(unittest.TestCase): """Test set fan mode.""" device = _get_device_heat_on() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertFalse(entity.should_poll) + assert not entity.should_poll entity.set_fan_mode(dyson.STATE_FOCUS) set_config = device.set_configuration @@ -237,27 +237,27 @@ class DysonTest(unittest.TestCase): """Test get fan list.""" device = _get_device_heat_on() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(len(entity.fan_list), 2) - self.assertTrue(dyson.STATE_FOCUS in entity.fan_list) - self.assertTrue(dyson.STATE_DIFFUSE in entity.fan_list) + assert len(entity.fan_list) == 2 + assert dyson.STATE_FOCUS in entity.fan_list + assert dyson.STATE_DIFFUSE in entity.fan_list def test_dyson_fan_mode_focus(self): """Test fan focus mode.""" device = _get_device_focus() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(entity.current_fan_mode, dyson.STATE_FOCUS) + assert entity.current_fan_mode == dyson.STATE_FOCUS def test_dyson_fan_mode_diffuse(self): """Test fan diffuse mode.""" device = _get_device_diffuse() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(entity.current_fan_mode, dyson.STATE_DIFFUSE) + assert entity.current_fan_mode == dyson.STATE_DIFFUSE def test_dyson_set_operation_mode(self): """Test set operation mode.""" device = _get_device_heat_on() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertFalse(entity.should_poll) + assert not entity.should_poll entity.set_operation_mode(dyson.STATE_HEAT) set_config = device.set_configuration @@ -271,9 +271,9 @@ class DysonTest(unittest.TestCase): """Test get operation list.""" device = _get_device_heat_on() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(len(entity.operation_list), 2) - self.assertTrue(dyson.STATE_HEAT in entity.operation_list) - self.assertTrue(dyson.STATE_COOL in entity.operation_list) + assert len(entity.operation_list) == 2 + assert dyson.STATE_HEAT in entity.operation_list + assert dyson.STATE_COOL in entity.operation_list def test_dyson_heat_off(self): """Test turn off heat.""" @@ -295,19 +295,19 @@ class DysonTest(unittest.TestCase): """Test get heat value on.""" device = _get_device_heat_on() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(entity.current_operation, dyson.STATE_HEAT) + assert entity.current_operation == dyson.STATE_HEAT def test_dyson_heat_value_off(self): """Test get heat value off.""" device = _get_device_cool() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(entity.current_operation, dyson.STATE_COOL) + assert entity.current_operation == dyson.STATE_COOL def test_dyson_heat_value_idle(self): """Test get heat value idle.""" device = _get_device_heat_off() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(entity.current_operation, dyson.STATE_IDLE) + assert entity.current_operation == dyson.STATE_IDLE def test_on_message(self): """Test when message is received.""" @@ -321,38 +321,38 @@ class DysonTest(unittest.TestCase): """Test properties of entity.""" device = _get_device_with_no_state() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(entity.should_poll, False) - self.assertEqual(entity.supported_features, dyson.SUPPORT_FLAGS) - self.assertEqual(entity.temperature_unit, TEMP_CELSIUS) + assert entity.should_poll is False + assert entity.supported_features == dyson.SUPPORT_FLAGS + assert entity.temperature_unit == TEMP_CELSIUS def test_property_current_humidity(self): """Test properties of current humidity.""" device = _get_device_heat_on() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(entity.current_humidity, 53) + assert entity.current_humidity == 53 def test_property_current_humidity_with_invalid_env_state(self): """Test properties of current humidity with invalid env state.""" device = _get_device_off() device.environmental_state.humidity = 0 entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(entity.current_humidity, None) + assert entity.current_humidity is None def test_property_current_humidity_without_env_state(self): """Test properties of current humidity without env state.""" device = _get_device_with_no_state() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(entity.current_humidity, None) + assert entity.current_humidity is None def test_property_current_temperature(self): """Test properties of current temperature.""" device = _get_device_heat_on() entity = dyson.DysonPureHotCoolLinkDevice(device) # Result should be in celsius, hence then subtraction of 273. - self.assertEqual(entity.current_temperature, 289 - 273) + assert entity.current_temperature == 289 - 273 def test_property_target_temperature(self): """Test properties of target temperature.""" device = _get_device_heat_on() entity = dyson.DysonPureHotCoolLinkDevice(device) - self.assertEqual(entity.target_temperature, 23) + assert entity.target_temperature == 23 diff --git a/tests/components/climate/test_ecobee.py b/tests/components/climate/test_ecobee.py index eb843d8eb..8a03cbcd1 100644 --- a/tests/components/climate/test_ecobee.py +++ b/tests/components/climate/test_ecobee.py @@ -44,214 +44,214 @@ class TestEcobee(unittest.TestCase): def test_name(self): """Test name property.""" - self.assertEqual('Ecobee', self.thermostat.name) + assert 'Ecobee' == self.thermostat.name def test_temperature_unit(self): """Test temperature unit property.""" - self.assertEqual(const.TEMP_FAHRENHEIT, - self.thermostat.temperature_unit) + assert const.TEMP_FAHRENHEIT == \ + self.thermostat.temperature_unit def test_current_temperature(self): """Test current temperature.""" - self.assertEqual(30, self.thermostat.current_temperature) + assert 30 == self.thermostat.current_temperature self.ecobee['runtime']['actualTemperature'] = 404 - self.assertEqual(40.4, self.thermostat.current_temperature) + assert 40.4 == self.thermostat.current_temperature def test_target_temperature_low(self): """Test target low temperature.""" - self.assertEqual(40, self.thermostat.target_temperature_low) + assert 40 == self.thermostat.target_temperature_low self.ecobee['runtime']['desiredHeat'] = 502 - self.assertEqual(50.2, self.thermostat.target_temperature_low) + assert 50.2 == self.thermostat.target_temperature_low def test_target_temperature_high(self): """Test target high temperature.""" - self.assertEqual(20, self.thermostat.target_temperature_high) + assert 20 == self.thermostat.target_temperature_high self.ecobee['runtime']['desiredCool'] = 103 - self.assertEqual(10.3, self.thermostat.target_temperature_high) + assert 10.3 == self.thermostat.target_temperature_high def test_target_temperature(self): """Test target temperature.""" - self.assertIsNone(self.thermostat.target_temperature) + assert self.thermostat.target_temperature is None self.ecobee['settings']['hvacMode'] = 'heat' - self.assertEqual(40, self.thermostat.target_temperature) + assert 40 == self.thermostat.target_temperature self.ecobee['settings']['hvacMode'] = 'cool' - self.assertEqual(20, self.thermostat.target_temperature) + assert 20 == self.thermostat.target_temperature self.ecobee['settings']['hvacMode'] = 'auxHeatOnly' - self.assertEqual(40, self.thermostat.target_temperature) + assert 40 == self.thermostat.target_temperature self.ecobee['settings']['hvacMode'] = 'off' - self.assertIsNone(self.thermostat.target_temperature) + assert self.thermostat.target_temperature is None def test_desired_fan_mode(self): """Test desired fan mode property.""" - self.assertEqual('on', self.thermostat.current_fan_mode) + assert 'on' == self.thermostat.current_fan_mode self.ecobee['runtime']['desiredFanMode'] = 'auto' - self.assertEqual('auto', self.thermostat.current_fan_mode) + assert 'auto' == self.thermostat.current_fan_mode def test_fan(self): """Test fan property.""" - self.assertEqual(const.STATE_ON, self.thermostat.fan) + assert const.STATE_ON == self.thermostat.fan self.ecobee['equipmentStatus'] = '' - self.assertEqual(STATE_OFF, self.thermostat.fan) + assert STATE_OFF == self.thermostat.fan self.ecobee['equipmentStatus'] = 'heatPump, heatPump2' - self.assertEqual(STATE_OFF, self.thermostat.fan) + assert STATE_OFF == self.thermostat.fan def test_current_hold_mode_away_temporary(self): """Test current hold mode when away.""" # Temporary away hold - self.assertEqual('away', self.thermostat.current_hold_mode) + assert 'away' == self.thermostat.current_hold_mode self.ecobee['events'][0]['endDate'] = '2018-01-01 09:49:00' - self.assertEqual('away', self.thermostat.current_hold_mode) + assert 'away' == self.thermostat.current_hold_mode def test_current_hold_mode_away_permanent(self): """Test current hold mode when away permanently.""" # Permanent away hold self.ecobee['events'][0]['endDate'] = '2019-01-01 10:17:00' - self.assertIsNone(self.thermostat.current_hold_mode) + assert self.thermostat.current_hold_mode is None def test_current_hold_mode_no_running_events(self): """Test current hold mode when no running events.""" # No running events self.ecobee['events'][0]['running'] = False - self.assertIsNone(self.thermostat.current_hold_mode) + assert self.thermostat.current_hold_mode is None def test_current_hold_mode_vacation(self): """Test current hold mode when on vacation.""" # Vacation Hold self.ecobee['events'][0]['type'] = 'vacation' - self.assertEqual('vacation', self.thermostat.current_hold_mode) + assert 'vacation' == self.thermostat.current_hold_mode def test_current_hold_mode_climate(self): """Test current hold mode when heat climate is set.""" # Preset climate hold self.ecobee['events'][0]['type'] = 'hold' self.ecobee['events'][0]['holdClimateRef'] = 'heatClimate' - self.assertEqual('heatClimate', self.thermostat.current_hold_mode) + assert 'heatClimate' == self.thermostat.current_hold_mode def test_current_hold_mode_temperature_hold(self): """Test current hold mode when temperature hold is set.""" # Temperature hold self.ecobee['events'][0]['type'] = 'hold' self.ecobee['events'][0]['holdClimateRef'] = '' - self.assertEqual('temp', self.thermostat.current_hold_mode) + assert 'temp' == self.thermostat.current_hold_mode def test_current_hold_mode_auto_hold(self): """Test current hold mode when auto heat is set.""" # auto Hold self.ecobee['events'][0]['type'] = 'autoHeat' - self.assertEqual('heat', self.thermostat.current_hold_mode) + assert 'heat' == self.thermostat.current_hold_mode def test_current_operation(self): """Test current operation property.""" - self.assertEqual('auto', self.thermostat.current_operation) + assert 'auto' == self.thermostat.current_operation self.ecobee['settings']['hvacMode'] = 'heat' - self.assertEqual('heat', self.thermostat.current_operation) + assert 'heat' == self.thermostat.current_operation self.ecobee['settings']['hvacMode'] = 'cool' - self.assertEqual('cool', self.thermostat.current_operation) + assert 'cool' == self.thermostat.current_operation self.ecobee['settings']['hvacMode'] = 'auxHeatOnly' - self.assertEqual('heat', self.thermostat.current_operation) + assert 'heat' == self.thermostat.current_operation self.ecobee['settings']['hvacMode'] = 'off' - self.assertEqual('off', self.thermostat.current_operation) + assert 'off' == self.thermostat.current_operation def test_operation_list(self): """Test operation list property.""" - self.assertEqual(['auto', 'auxHeatOnly', 'cool', - 'heat', 'off'], self.thermostat.operation_list) + assert ['auto', 'auxHeatOnly', 'cool', + 'heat', 'off'] == self.thermostat.operation_list def test_operation_mode(self): """Test operation mode property.""" - self.assertEqual('auto', self.thermostat.operation_mode) + assert 'auto' == self.thermostat.operation_mode self.ecobee['settings']['hvacMode'] = 'heat' - self.assertEqual('heat', self.thermostat.operation_mode) + assert 'heat' == self.thermostat.operation_mode def test_mode(self): """Test mode property.""" - self.assertEqual('Climate1', self.thermostat.mode) + assert 'Climate1' == self.thermostat.mode self.ecobee['program']['currentClimateRef'] = 'c2' - self.assertEqual('Climate2', self.thermostat.mode) + assert 'Climate2' == self.thermostat.mode def test_fan_min_on_time(self): """Test fan min on time property.""" - self.assertEqual(10, self.thermostat.fan_min_on_time) + assert 10 == self.thermostat.fan_min_on_time self.ecobee['settings']['fanMinOnTime'] = 100 - self.assertEqual(100, self.thermostat.fan_min_on_time) + assert 100 == self.thermostat.fan_min_on_time def test_device_state_attributes(self): """Test device state attributes property.""" self.ecobee['equipmentStatus'] = 'heatPump2' - self.assertEqual({'actual_humidity': 15, - 'climate_list': ['Climate1', 'Climate2'], - 'fan': 'off', - 'fan_min_on_time': 10, - 'climate_mode': 'Climate1', - 'operation': 'heat'}, - self.thermostat.device_state_attributes) + assert {'actual_humidity': 15, + 'climate_list': ['Climate1', 'Climate2'], + 'fan': 'off', + 'fan_min_on_time': 10, + 'climate_mode': 'Climate1', + 'operation': 'heat'} == \ + self.thermostat.device_state_attributes self.ecobee['equipmentStatus'] = 'auxHeat2' - self.assertEqual({'actual_humidity': 15, - 'climate_list': ['Climate1', 'Climate2'], - 'fan': 'off', - 'fan_min_on_time': 10, - 'climate_mode': 'Climate1', - 'operation': 'heat'}, - self.thermostat.device_state_attributes) + assert {'actual_humidity': 15, + 'climate_list': ['Climate1', 'Climate2'], + 'fan': 'off', + 'fan_min_on_time': 10, + 'climate_mode': 'Climate1', + 'operation': 'heat'} == \ + self.thermostat.device_state_attributes self.ecobee['equipmentStatus'] = 'compCool1' - self.assertEqual({'actual_humidity': 15, - 'climate_list': ['Climate1', 'Climate2'], - 'fan': 'off', - 'fan_min_on_time': 10, - 'climate_mode': 'Climate1', - 'operation': 'cool'}, - self.thermostat.device_state_attributes) + assert {'actual_humidity': 15, + 'climate_list': ['Climate1', 'Climate2'], + 'fan': 'off', + 'fan_min_on_time': 10, + 'climate_mode': 'Climate1', + 'operation': 'cool'} == \ + self.thermostat.device_state_attributes self.ecobee['equipmentStatus'] = '' - self.assertEqual({'actual_humidity': 15, - 'climate_list': ['Climate1', 'Climate2'], - 'fan': 'off', - 'fan_min_on_time': 10, - 'climate_mode': 'Climate1', - 'operation': 'idle'}, - self.thermostat.device_state_attributes) + assert {'actual_humidity': 15, + 'climate_list': ['Climate1', 'Climate2'], + 'fan': 'off', + 'fan_min_on_time': 10, + 'climate_mode': 'Climate1', + 'operation': 'idle'} == \ + self.thermostat.device_state_attributes self.ecobee['equipmentStatus'] = 'Unknown' - self.assertEqual({'actual_humidity': 15, - 'climate_list': ['Climate1', 'Climate2'], - 'fan': 'off', - 'fan_min_on_time': 10, - 'climate_mode': 'Climate1', - 'operation': 'Unknown'}, - self.thermostat.device_state_attributes) + assert {'actual_humidity': 15, + 'climate_list': ['Climate1', 'Climate2'], + 'fan': 'off', + 'fan_min_on_time': 10, + 'climate_mode': 'Climate1', + 'operation': 'Unknown'} == \ + self.thermostat.device_state_attributes def test_is_away_mode_on(self): """Test away mode property.""" - self.assertFalse(self.thermostat.is_away_mode_on) + assert not self.thermostat.is_away_mode_on # Temporary away hold self.ecobee['events'][0]['endDate'] = '2018-01-01 11:12:12' - self.assertFalse(self.thermostat.is_away_mode_on) + assert not self.thermostat.is_away_mode_on # Permanent away hold self.ecobee['events'][0]['endDate'] = '2019-01-01 13:12:12' - self.assertTrue(self.thermostat.is_away_mode_on) + assert self.thermostat.is_away_mode_on # No running events self.ecobee['events'][0]['running'] = False - self.assertFalse(self.thermostat.is_away_mode_on) + assert not self.thermostat.is_away_mode_on # Vacation Hold self.ecobee['events'][0]['type'] = 'vacation' - self.assertFalse(self.thermostat.is_away_mode_on) + assert not self.thermostat.is_away_mode_on # Preset climate hold self.ecobee['events'][0]['type'] = 'hold' self.ecobee['events'][0]['holdClimateRef'] = 'heatClimate' - self.assertFalse(self.thermostat.is_away_mode_on) + assert not self.thermostat.is_away_mode_on # Temperature hold self.ecobee['events'][0]['type'] = 'hold' self.ecobee['events'][0]['holdClimateRef'] = '' - self.assertFalse(self.thermostat.is_away_mode_on) + assert not self.thermostat.is_away_mode_on # auto Hold self.ecobee['events'][0]['type'] = 'autoHeat' - self.assertFalse(self.thermostat.is_away_mode_on) + assert not self.thermostat.is_away_mode_on def test_is_aux_heat_on(self): """Test aux heat property.""" - self.assertFalse(self.thermostat.is_aux_heat_on) + assert not self.thermostat.is_aux_heat_on self.ecobee['equipmentStatus'] = 'fan, auxHeat' - self.assertTrue(self.thermostat.is_aux_heat_on) + assert self.thermostat.is_aux_heat_on def test_turn_away_mode_on_off(self): """Test turn away mode setter.""" @@ -265,7 +265,7 @@ class TestEcobee(unittest.TestCase): self.data.reset_mock() self.ecobee['events'][0]['endDate'] = '2019-01-01 11:12:12' # Should not call set_climate_hold() - self.assertFalse(self.data.ecobee.set_climate_hold.called) + assert not self.data.ecobee.set_climate_hold.called # Try turning off while hold mode is away hold self.data.reset_mock() @@ -276,7 +276,7 @@ class TestEcobee(unittest.TestCase): self.data.reset_mock() self.ecobee['events'][0]['endDate'] = '2017-01-01 14:00:00' self.thermostat.turn_away_mode_off() - self.assertFalse(self.data.ecobee.resume_program.called) + assert not self.data.ecobee.resume_program.called def test_set_hold_mode(self): """Test hold mode setter.""" @@ -284,18 +284,18 @@ class TestEcobee(unittest.TestCase): # Away->Away self.data.reset_mock() self.thermostat.set_hold_mode('away') - self.assertFalse(self.data.ecobee.delete_vacation.called) - self.assertFalse(self.data.ecobee.resume_program.called) - self.assertFalse(self.data.ecobee.set_hold_temp.called) - self.assertFalse(self.data.ecobee.set_climate_hold.called) + assert not self.data.ecobee.delete_vacation.called + assert not self.data.ecobee.resume_program.called + assert not self.data.ecobee.set_hold_temp.called + assert not self.data.ecobee.set_climate_hold.called # Away->'None' self.data.reset_mock() self.thermostat.set_hold_mode('None') - self.assertFalse(self.data.ecobee.delete_vacation.called) + assert not self.data.ecobee.delete_vacation.called self.data.ecobee.resume_program.assert_has_calls([mock.call(1)]) - self.assertFalse(self.data.ecobee.set_hold_temp.called) - self.assertFalse(self.data.ecobee.set_climate_hold.called) + assert not self.data.ecobee.set_hold_temp.called + assert not self.data.ecobee.set_climate_hold.called # Vacation Hold -> None self.ecobee['events'][0]['type'] = 'vacation' @@ -303,28 +303,28 @@ class TestEcobee(unittest.TestCase): self.thermostat.set_hold_mode(None) self.data.ecobee.delete_vacation.assert_has_calls( [mock.call(1, 'Event1')]) - self.assertFalse(self.data.ecobee.resume_program.called) - self.assertFalse(self.data.ecobee.set_hold_temp.called) - self.assertFalse(self.data.ecobee.set_climate_hold.called) + assert not self.data.ecobee.resume_program.called + assert not self.data.ecobee.set_hold_temp.called + assert not self.data.ecobee.set_climate_hold.called # Away -> home, sleep for hold in ['home', 'sleep']: self.data.reset_mock() self.thermostat.set_hold_mode(hold) - self.assertFalse(self.data.ecobee.delete_vacation.called) - self.assertFalse(self.data.ecobee.resume_program.called) - self.assertFalse(self.data.ecobee.set_hold_temp.called) + assert not self.data.ecobee.delete_vacation.called + assert not self.data.ecobee.resume_program.called + assert not self.data.ecobee.set_hold_temp.called self.data.ecobee.set_climate_hold.assert_has_calls( [mock.call(1, hold, 'nextTransition')]) # Away -> temp self.data.reset_mock() self.thermostat.set_hold_mode('temp') - self.assertFalse(self.data.ecobee.delete_vacation.called) - self.assertFalse(self.data.ecobee.resume_program.called) + assert not self.data.ecobee.delete_vacation.called + assert not self.data.ecobee.resume_program.called self.data.ecobee.set_hold_temp.assert_has_calls( [mock.call(1, 35.0, 25.0, 'nextTransition')]) - self.assertFalse(self.data.ecobee.set_climate_hold.called) + assert not self.data.ecobee.set_climate_hold.called def test_set_auto_temp_hold(self): """Test auto temp hold setter.""" @@ -389,7 +389,7 @@ class TestEcobee(unittest.TestCase): self.ecobee['settings']['hvacMode'] = 'heat' self.thermostat.set_temperature(target_temp_low=20, target_temp_high=30) - self.assertFalse(self.data.ecobee.set_hold_temp.called) + assert not self.data.ecobee.set_hold_temp.called def test_set_operation_mode(self): """Test operation mode setter.""" @@ -441,17 +441,17 @@ class TestEcobee(unittest.TestCase): def test_hold_preference(self): """Test hold preference.""" - self.assertEqual('nextTransition', self.thermostat.hold_preference()) + assert 'nextTransition' == self.thermostat.hold_preference() for action in ['useEndTime4hour', 'useEndTime2hour', 'nextPeriod', 'indefinite', 'askMe']: self.ecobee['settings']['holdAction'] = action - self.assertEqual('nextTransition', - self.thermostat.hold_preference()) + assert 'nextTransition' == \ + self.thermostat.hold_preference() def test_climate_list(self): """Test climate list property.""" - self.assertEqual(['Climate1', 'Climate2'], - self.thermostat.climate_list) + assert ['Climate1', 'Climate2'] == \ + self.thermostat.climate_list def test_set_fan_mode_on(self): """Test set fan mode to on.""" diff --git a/tests/components/climate/test_fritzbox.py b/tests/components/climate/test_fritzbox.py index ccffef9e5..1cd15e365 100644 --- a/tests/components/climate/test_fritzbox.py +++ b/tests/components/climate/test_fritzbox.py @@ -30,46 +30,46 @@ class TestFritzboxClimate(unittest.TestCase): def test_init(self): """Test instance creation.""" - self.assertEqual(18.0, self.thermostat._current_temperature) - self.assertEqual(19.5, self.thermostat._target_temperature) - self.assertEqual(22.0, self.thermostat._comfort_temperature) - self.assertEqual(16.0, self.thermostat._eco_temperature) + assert 18.0 == self.thermostat._current_temperature + assert 19.5 == self.thermostat._target_temperature + assert 22.0 == self.thermostat._comfort_temperature + assert 16.0 == self.thermostat._eco_temperature def test_supported_features(self): """Test supported features property.""" - self.assertEqual(129, self.thermostat.supported_features) + assert 129 == self.thermostat.supported_features def test_available(self): """Test available property.""" - self.assertTrue(self.thermostat.available) + assert self.thermostat.available self.thermostat._device.present = False - self.assertFalse(self.thermostat.available) + assert not self.thermostat.available def test_name(self): """Test name property.""" - self.assertEqual('Test Thermostat', self.thermostat.name) + assert 'Test Thermostat' == self.thermostat.name def test_temperature_unit(self): """Test temperature_unit property.""" - self.assertEqual('°C', self.thermostat.temperature_unit) + assert '°C' == self.thermostat.temperature_unit def test_precision(self): """Test precision property.""" - self.assertEqual(0.5, self.thermostat.precision) + assert 0.5 == self.thermostat.precision def test_current_temperature(self): """Test current_temperature property incl. special temperatures.""" - self.assertEqual(18, self.thermostat.current_temperature) + assert 18 == self.thermostat.current_temperature def test_target_temperature(self): """Test target_temperature property.""" - self.assertEqual(19.5, self.thermostat.target_temperature) + assert 19.5 == self.thermostat.target_temperature self.thermostat._target_temperature = 126.5 - self.assertEqual(None, self.thermostat.target_temperature) + assert self.thermostat.target_temperature is None self.thermostat._target_temperature = 127.0 - self.assertEqual(None, self.thermostat.target_temperature) + assert self.thermostat.target_temperature is None @patch.object(FritzboxThermostat, 'set_operation_mode') def test_set_temperature_operation_mode(self, mock_set_op): @@ -101,20 +101,20 @@ class TestFritzboxClimate(unittest.TestCase): def test_current_operation(self): """Test operation mode property for different temperatures.""" self.thermostat._target_temperature = 127.0 - self.assertEqual('on', self.thermostat.current_operation) + assert 'on' == self.thermostat.current_operation self.thermostat._target_temperature = 126.5 - self.assertEqual('off', self.thermostat.current_operation) + assert 'off' == self.thermostat.current_operation self.thermostat._target_temperature = 22.0 - self.assertEqual('heat', self.thermostat.current_operation) + assert 'heat' == self.thermostat.current_operation self.thermostat._target_temperature = 16.0 - self.assertEqual('eco', self.thermostat.current_operation) + assert 'eco' == self.thermostat.current_operation self.thermostat._target_temperature = 12.5 - self.assertEqual('manual', self.thermostat.current_operation) + assert 'manual' == self.thermostat.current_operation def test_operation_list(self): """Test operation_list property.""" - self.assertEqual(['heat', 'eco', 'off', 'on'], - self.thermostat.operation_list) + assert ['heat', 'eco', 'off', 'on'] == \ + self.thermostat.operation_list @patch.object(FritzboxThermostat, 'set_temperature') def test_set_operation_mode(self, mock_set_temp): @@ -137,15 +137,15 @@ class TestFritzboxClimate(unittest.TestCase): def test_min_max_temperature(self): """Test min_temp and max_temp properties.""" - self.assertEqual(8.0, self.thermostat.min_temp) - self.assertEqual(28.0, self.thermostat.max_temp) + assert 8.0 == self.thermostat.min_temp + assert 28.0 == self.thermostat.max_temp def test_device_state_attributes(self): """Test device_state property.""" attr = self.thermostat.device_state_attributes - self.assertEqual(attr['device_locked'], True) - self.assertEqual(attr['locked'], False) - self.assertEqual(attr['battery_low'], True) + assert attr['device_locked'] is True + assert attr['locked'] is False + assert attr['battery_low'] is True def test_update(self): """Test update function.""" @@ -160,10 +160,10 @@ class TestFritzboxClimate(unittest.TestCase): self.thermostat.update() device.update.assert_called_once_with() - self.assertEqual(10.0, self.thermostat._current_temperature) - self.assertEqual(11.0, self.thermostat._target_temperature) - self.assertEqual(12.0, self.thermostat._comfort_temperature) - self.assertEqual(13.0, self.thermostat._eco_temperature) + assert 10.0 == self.thermostat._current_temperature + assert 11.0 == self.thermostat._target_temperature + assert 12.0 == self.thermostat._comfort_temperature + assert 13.0 == self.thermostat._eco_temperature def test_update_http_error(self): """Test exception handling of update function.""" diff --git a/tests/components/climate/test_generic_thermostat.py b/tests/components/climate/test_generic_thermostat.py index 8bbcbc8f8..71654afd5 100644 --- a/tests/components/climate/test_generic_thermostat.py +++ b/tests/components/climate/test_generic_thermostat.py @@ -62,15 +62,13 @@ class TestSetupClimateGenericThermostat(unittest.TestCase): def test_valid_conf(self): """Test set up generic_thermostat with valid config values.""" - self.assertTrue( - setup_component(self.hass, 'climate', - {'climate': { - 'platform': 'generic_thermostat', - 'name': 'test', - 'heater': ENT_SWITCH, - 'target_sensor': ENT_SENSOR - }}) - ) + assert setup_component(self.hass, 'climate', { + 'climate': { + 'platform': 'generic_thermostat', + 'name': 'test', + 'heater': ENT_SWITCH, + 'target_sensor': ENT_SENSOR + }}) class TestGenericThermostatHeaterSwitching(unittest.TestCase): @@ -83,9 +81,9 @@ class TestGenericThermostatHeaterSwitching(unittest.TestCase): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.units = METRIC_SYSTEM - self.assertTrue(run_coroutine_threadsafe( + assert run_coroutine_threadsafe( comps.async_setup(self.hass, {}), self.hass.loop - ).result()) + ).result() def tearDown(self): # pylint: disable=invalid-name """Stop down everything that was started.""" @@ -104,16 +102,16 @@ class TestGenericThermostatHeaterSwitching(unittest.TestCase): 'target_sensor': ENT_SENSOR }}) - self.assertEqual(STATE_OFF, - self.hass.states.get(heater_switch).state) + assert STATE_OFF == \ + self.hass.states.get(heater_switch).state self._setup_sensor(18) self.hass.block_till_done() common.set_temperature(self.hass, 23) self.hass.block_till_done() - self.assertEqual(STATE_ON, - self.hass.states.get(heater_switch).state) + assert STATE_ON == \ + self.hass.states.get(heater_switch).state def test_heater_switch(self): """Test heater switching test switch.""" @@ -131,16 +129,16 @@ class TestGenericThermostatHeaterSwitching(unittest.TestCase): 'target_sensor': ENT_SENSOR }}) - self.assertEqual(STATE_OFF, - self.hass.states.get(heater_switch).state) + assert STATE_OFF == \ + self.hass.states.get(heater_switch).state self._setup_sensor(18) self.hass.block_till_done() common.set_temperature(self.hass, 23) self.hass.block_till_done() - self.assertEqual(STATE_ON, - self.hass.states.get(heater_switch).state) + assert STATE_ON == \ + self.hass.states.get(heater_switch).state def _setup_sensor(self, temp): """Set up the test sensor.""" @@ -170,31 +168,31 @@ class TestClimateGenericThermostat(unittest.TestCase): def test_setup_defaults_to_unknown(self): """Test the setting of defaults to unknown.""" - self.assertEqual(STATE_IDLE, self.hass.states.get(ENTITY).state) + assert STATE_IDLE == self.hass.states.get(ENTITY).state def test_default_setup_params(self): """Test the setup with default parameters.""" state = self.hass.states.get(ENTITY) - self.assertEqual(7, state.attributes.get('min_temp')) - self.assertEqual(35, state.attributes.get('max_temp')) - self.assertEqual(7, state.attributes.get('temperature')) + assert 7 == state.attributes.get('min_temp') + assert 35 == state.attributes.get('max_temp') + assert 7 == state.attributes.get('temperature') def test_get_operation_modes(self): """Test that the operation list returns the correct modes.""" state = self.hass.states.get(ENTITY) modes = state.attributes.get('operation_list') - self.assertEqual([climate.STATE_HEAT, STATE_OFF], modes) + assert [climate.STATE_HEAT, STATE_OFF] == modes def test_set_target_temp(self): """Test the setting of the target temperature.""" common.set_temperature(self.hass, 30) self.hass.block_till_done() state = self.hass.states.get(ENTITY) - self.assertEqual(30.0, state.attributes.get('temperature')) + assert 30.0 == state.attributes.get('temperature') common.set_temperature(self.hass, None) self.hass.block_till_done() state = self.hass.states.get(ENTITY) - self.assertEqual(30.0, state.attributes.get('temperature')) + assert 30.0 == state.attributes.get('temperature') def test_set_away_mode(self): """Test the setting away mode.""" @@ -203,7 +201,7 @@ class TestClimateGenericThermostat(unittest.TestCase): common.set_away_mode(self.hass, True) self.hass.block_till_done() state = self.hass.states.get(ENTITY) - self.assertEqual(16, state.attributes.get('temperature')) + assert 16 == state.attributes.get('temperature') def test_set_away_mode_and_restore_prev_temp(self): """Test the setting and removing away mode. @@ -215,11 +213,11 @@ class TestClimateGenericThermostat(unittest.TestCase): common.set_away_mode(self.hass, True) self.hass.block_till_done() state = self.hass.states.get(ENTITY) - self.assertEqual(16, state.attributes.get('temperature')) + assert 16 == state.attributes.get('temperature') common.set_away_mode(self.hass, False) self.hass.block_till_done() state = self.hass.states.get(ENTITY) - self.assertEqual(23, state.attributes.get('temperature')) + assert 23 == state.attributes.get('temperature') def test_set_away_mode_twice_and_restore_prev_temp(self): """Test the setting away mode twice in a row. @@ -233,11 +231,11 @@ class TestClimateGenericThermostat(unittest.TestCase): common.set_away_mode(self.hass, True) self.hass.block_till_done() state = self.hass.states.get(ENTITY) - self.assertEqual(16, state.attributes.get('temperature')) + assert 16 == state.attributes.get('temperature') common.set_away_mode(self.hass, False) self.hass.block_till_done() state = self.hass.states.get(ENTITY) - self.assertEqual(23, state.attributes.get('temperature')) + assert 23 == state.attributes.get('temperature') def test_sensor_bad_value(self): """Test sensor that have None as state.""" @@ -248,7 +246,7 @@ class TestClimateGenericThermostat(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(ENTITY) - self.assertEqual(temp, state.attributes.get('current_temperature')) + assert temp == state.attributes.get('current_temperature') def test_set_target_temp_heater_on(self): """Test if target temperature turn heater on.""" @@ -257,11 +255,11 @@ class TestClimateGenericThermostat(unittest.TestCase): self.hass.block_till_done() common.set_temperature(self.hass, 30) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_ON, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_ON == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_set_target_temp_heater_off(self): """Test if target temperature turn heater off.""" @@ -270,11 +268,11 @@ class TestClimateGenericThermostat(unittest.TestCase): self.hass.block_till_done() common.set_temperature(self.hass, 25) self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_OFF == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_temp_change_heater_on_within_tolerance(self): """Test if temperature change doesn't turn on within tolerance.""" @@ -283,7 +281,7 @@ class TestClimateGenericThermostat(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(29) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_temp_change_heater_on_outside_tolerance(self): """Test if temperature change turn heater on outside cold tolerance.""" @@ -292,11 +290,11 @@ class TestClimateGenericThermostat(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(27) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_ON, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_ON == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_temp_change_heater_off_within_tolerance(self): """Test if temperature change doesn't turn off within tolerance.""" @@ -305,7 +303,7 @@ class TestClimateGenericThermostat(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(33) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_temp_change_heater_off_outside_tolerance(self): """Test if temperature change turn heater off outside hot tolerance.""" @@ -314,11 +312,11 @@ class TestClimateGenericThermostat(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(35) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_OFF == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_running_when_operating_mode_is_off(self): """Test that the switch turns off when enabled is set False.""" @@ -327,11 +325,11 @@ class TestClimateGenericThermostat(unittest.TestCase): self.hass.block_till_done() common.set_operation_mode(self.hass, STATE_OFF) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_OFF == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_no_state_change_when_operation_mode_off(self): """Test that the switch doesn't turn on when enabled is False.""" @@ -342,14 +340,14 @@ class TestClimateGenericThermostat(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(25) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) @mock.patch('logging.Logger.error') def test_invalid_operating_mode(self, log_mock): """Test error handling for invalid operation mode.""" common.set_operation_mode(self.hass, 'invalid mode') self.hass.block_till_done() - self.assertEqual(log_mock.call_count, 1) + assert log_mock.call_count == 1 def test_operating_mode_heat(self): """Test change mode from OFF to HEAT. @@ -363,11 +361,11 @@ class TestClimateGenericThermostat(unittest.TestCase): self._setup_switch(False) common.set_operation_mode(self.hass, climate.STATE_HEAT) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_ON, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_ON == call.service + assert ENT_SWITCH == call.data['entity_id'] def _setup_sensor(self, temp): """Set up the test sensor.""" @@ -416,11 +414,11 @@ class TestClimateGenericThermostatACMode(unittest.TestCase): self.hass.block_till_done() common.set_temperature(self.hass, 30) self.hass.block_till_done() - self.assertEqual(2, len(self.calls)) + assert 2 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_OFF == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_turn_away_mode_on_cooling(self): """Test the setting away mode when cooling.""" @@ -431,7 +429,7 @@ class TestClimateGenericThermostatACMode(unittest.TestCase): common.set_away_mode(self.hass, True) self.hass.block_till_done() state = self.hass.states.get(ENTITY) - self.assertEqual(30, state.attributes.get('temperature')) + assert 30 == state.attributes.get('temperature') def test_operating_mode_cool(self): """Test change mode from OFF to COOL. @@ -445,11 +443,11 @@ class TestClimateGenericThermostatACMode(unittest.TestCase): self._setup_switch(False) common.set_operation_mode(self.hass, climate.STATE_COOL) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_ON, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_ON == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_set_target_temp_ac_on(self): """Test if target temperature turn ac on.""" @@ -458,11 +456,11 @@ class TestClimateGenericThermostatACMode(unittest.TestCase): self.hass.block_till_done() common.set_temperature(self.hass, 25) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_ON, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_ON == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_temp_change_ac_off_within_tolerance(self): """Test if temperature change doesn't turn ac off within tolerance.""" @@ -471,7 +469,7 @@ class TestClimateGenericThermostatACMode(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(29.8) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_set_temp_change_ac_off_outside_tolerance(self): """Test if temperature change turn ac off.""" @@ -480,11 +478,11 @@ class TestClimateGenericThermostatACMode(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(27) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_OFF == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_temp_change_ac_on_within_tolerance(self): """Test if temperature change doesn't turn ac on within tolerance.""" @@ -493,7 +491,7 @@ class TestClimateGenericThermostatACMode(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(25.2) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_temp_change_ac_on_outside_tolerance(self): """Test if temperature change turn ac on.""" @@ -502,11 +500,11 @@ class TestClimateGenericThermostatACMode(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(30) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_ON, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_ON == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_running_when_operating_mode_is_off(self): """Test that the switch turns off when enabled is set False.""" @@ -515,11 +513,11 @@ class TestClimateGenericThermostatACMode(unittest.TestCase): self.hass.block_till_done() common.set_operation_mode(self.hass, STATE_OFF) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_OFF == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_no_state_change_when_operation_mode_off(self): """Test that the switch doesn't turn on when enabled is False.""" @@ -530,7 +528,7 @@ class TestClimateGenericThermostatACMode(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(35) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def _setup_sensor(self, temp): """Set up the test sensor.""" @@ -579,7 +577,7 @@ class TestClimateGenericThermostatACModeMinCycle(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(30) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_temp_change_ac_trigger_on_long_enough(self): """Test if temperature change turn ac on.""" @@ -592,11 +590,11 @@ class TestClimateGenericThermostatACModeMinCycle(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(30) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_ON, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_ON == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_temp_change_ac_trigger_off_not_long_enough(self): """Test if temperature change turn ac on.""" @@ -605,7 +603,7 @@ class TestClimateGenericThermostatACModeMinCycle(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(25) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_temp_change_ac_trigger_off_long_enough(self): """Test if temperature change turn ac on.""" @@ -618,11 +616,11 @@ class TestClimateGenericThermostatACModeMinCycle(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(25) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_OFF == call.service + assert ENT_SWITCH == call.data['entity_id'] def _setup_sensor(self, temp): """Set up the test sensor.""" @@ -670,7 +668,7 @@ class TestClimateGenericThermostatMinCycle(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(30) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_temp_change_heater_trigger_on_not_long_enough(self): """Test if temp change doesn't turn heater on because of time.""" @@ -679,7 +677,7 @@ class TestClimateGenericThermostatMinCycle(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(25) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_temp_change_heater_trigger_on_long_enough(self): """Test if temperature change turn heater on after min cycle.""" @@ -692,11 +690,11 @@ class TestClimateGenericThermostatMinCycle(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(25) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_ON, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_ON == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_temp_change_heater_trigger_off_long_enough(self): """Test if temperature change turn heater off after min cycle.""" @@ -709,11 +707,11 @@ class TestClimateGenericThermostatMinCycle(unittest.TestCase): self.hass.block_till_done() self._setup_sensor(30) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_OFF == call.service + assert ENT_SWITCH == call.data['entity_id'] def _setup_sensor(self, temp): """Set up the test sensor.""" @@ -767,17 +765,17 @@ class TestClimateGenericThermostatACKeepAlive(unittest.TestCase): test_time = datetime.datetime.now(pytz.UTC) self._send_time_changed(test_time) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) self._send_time_changed(test_time + datetime.timedelta(minutes=5)) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) self._send_time_changed(test_time + datetime.timedelta(minutes=10)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_ON, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_ON == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_temp_change_ac_trigger_off_long_enough(self): """Test if turn on signal is sent at keep-alive intervals.""" @@ -790,17 +788,17 @@ class TestClimateGenericThermostatACKeepAlive(unittest.TestCase): test_time = datetime.datetime.now(pytz.UTC) self._send_time_changed(test_time) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) self._send_time_changed(test_time + datetime.timedelta(minutes=5)) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) self._send_time_changed(test_time + datetime.timedelta(minutes=10)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_OFF == call.service + assert ENT_SWITCH == call.data['entity_id'] def _send_time_changed(self, now): """Send a time changed event.""" @@ -857,17 +855,17 @@ class TestClimateGenericThermostatKeepAlive(unittest.TestCase): test_time = datetime.datetime.now(pytz.UTC) self._send_time_changed(test_time) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) self._send_time_changed(test_time + datetime.timedelta(minutes=5)) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) self._send_time_changed(test_time + datetime.timedelta(minutes=10)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_ON, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_ON == call.service + assert ENT_SWITCH == call.data['entity_id'] def test_temp_change_heater_trigger_off_long_enough(self): """Test if turn on signal is sent at keep-alive intervals.""" @@ -880,17 +878,17 @@ class TestClimateGenericThermostatKeepAlive(unittest.TestCase): test_time = datetime.datetime.now(pytz.UTC) self._send_time_changed(test_time) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) self._send_time_changed(test_time + datetime.timedelta(minutes=5)) self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) self._send_time_changed(test_time + datetime.timedelta(minutes=10)) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) call = self.calls[0] - self.assertEqual('homeassistant', call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual(ENT_SWITCH, call.data['entity_id']) + assert 'homeassistant' == call.domain + assert SERVICE_TURN_OFF == call.service + assert ENT_SWITCH == call.data['entity_id'] def _send_time_changed(self, now): """Send a time changed event.""" @@ -951,10 +949,10 @@ class TestClimateGenericThermostatTurnOnOff(unittest.TestCase): self.hass.block_till_done() state_heat = self.hass.states.get(self.HEAT_ENTITY) state_cool = self.hass.states.get(self.COOL_ENTITY) - self.assertEqual(STATE_HEAT, - state_heat.attributes.get('operation_mode')) - self.assertEqual(STATE_COOL, - state_cool.attributes.get('operation_mode')) + assert STATE_HEAT == \ + state_heat.attributes.get('operation_mode') + assert STATE_COOL == \ + state_cool.attributes.get('operation_mode') def test_turn_on_when_on(self): """Test if climate.turn_on does nothing to a turned on device.""" @@ -965,10 +963,10 @@ class TestClimateGenericThermostatTurnOnOff(unittest.TestCase): self.hass.block_till_done() state_heat = self.hass.states.get(self.HEAT_ENTITY) state_cool = self.hass.states.get(self.COOL_ENTITY) - self.assertEqual(STATE_HEAT, - state_heat.attributes.get('operation_mode')) - self.assertEqual(STATE_COOL, - state_cool.attributes.get('operation_mode')) + assert STATE_HEAT == \ + state_heat.attributes.get('operation_mode') + assert STATE_COOL == \ + state_cool.attributes.get('operation_mode') def test_turn_off_when_on(self): """Test if climate.turn_off turns off a turned on device.""" @@ -979,10 +977,10 @@ class TestClimateGenericThermostatTurnOnOff(unittest.TestCase): self.hass.block_till_done() state_heat = self.hass.states.get(self.HEAT_ENTITY) state_cool = self.hass.states.get(self.COOL_ENTITY) - self.assertEqual(STATE_OFF, - state_heat.attributes.get('operation_mode')) - self.assertEqual(STATE_OFF, - state_cool.attributes.get('operation_mode')) + assert STATE_OFF == \ + state_heat.attributes.get('operation_mode') + assert STATE_OFF == \ + state_cool.attributes.get('operation_mode') def test_turn_off_when_off(self): """Test if climate.turn_off does nothing to a turned off device.""" @@ -992,10 +990,10 @@ class TestClimateGenericThermostatTurnOnOff(unittest.TestCase): self.hass.block_till_done() state_heat = self.hass.states.get(self.HEAT_ENTITY) state_cool = self.hass.states.get(self.COOL_ENTITY) - self.assertEqual(STATE_OFF, - state_heat.attributes.get('operation_mode')) - self.assertEqual(STATE_OFF, - state_cool.attributes.get('operation_mode')) + assert STATE_OFF == \ + state_heat.attributes.get('operation_mode') + assert STATE_OFF == \ + state_cool.attributes.get('operation_mode') @asyncio.coroutine @@ -1096,18 +1094,18 @@ class TestClimateGenericThermostatRestoreState(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(ENTITY) - self.assertEqual(20, state.attributes[ATTR_TEMPERATURE]) - self.assertEqual(STATE_OFF, - state.attributes[climate.ATTR_OPERATION_MODE]) - self.assertEqual(STATE_OFF, state.state) - self.assertEqual(0, len(self.calls)) + assert 20 == state.attributes[ATTR_TEMPERATURE] + assert STATE_OFF == \ + state.attributes[climate.ATTR_OPERATION_MODE] + assert STATE_OFF == state.state + assert 0 == len(self.calls) self._setup_switch(False) self.hass.block_till_done() state = self.hass.states.get(ENTITY) - self.assertEqual(STATE_OFF, - state.attributes[climate.ATTR_OPERATION_MODE]) - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == \ + state.attributes[climate.ATTR_OPERATION_MODE] + assert STATE_OFF == state.state def _setup_climate(self): assert setup_component(self.hass, climate.DOMAIN, {'climate': { diff --git a/tests/components/climate/test_honeywell.py b/tests/components/climate/test_honeywell.py index 707209059..7daed2ff4 100644 --- a/tests/components/climate/test_honeywell.py +++ b/tests/components/climate/test_honeywell.py @@ -12,6 +12,7 @@ from homeassistant.components.climate import ( ATTR_FAN_MODE, ATTR_OPERATION_MODE, ATTR_FAN_LIST, ATTR_OPERATION_LIST) import homeassistant.components.climate.honeywell as honeywell +import pytest class TestHoneywell(unittest.TestCase): @@ -43,16 +44,16 @@ class TestHoneywell(unittest.TestCase): honeywell.CONF_REGION: 'un', } - with self.assertRaises(vol.Invalid): + with pytest.raises(vol.Invalid): honeywell.PLATFORM_SCHEMA(None) - with self.assertRaises(vol.Invalid): + with pytest.raises(vol.Invalid): honeywell.PLATFORM_SCHEMA({}) - with self.assertRaises(vol.Invalid): + with pytest.raises(vol.Invalid): honeywell.PLATFORM_SCHEMA(bad_pass_config) - with self.assertRaises(vol.Invalid): + with pytest.raises(vol.Invalid): honeywell.PLATFORM_SCHEMA(bad_region_config) hass = mock.MagicMock() @@ -70,9 +71,9 @@ class TestHoneywell(unittest.TestCase): locations[1].devices_by_id.values.return_value = devices_2 result = honeywell.setup_platform(hass, config, add_entities) - self.assertTrue(result) - self.assertEqual(mock_sc.call_count, 1) - self.assertEqual(mock_sc.call_args, mock.call('user', 'pass')) + assert result + assert mock_sc.call_count == 1 + assert mock_sc.call_args == mock.call('user', 'pass') mock_ht.assert_has_calls([ mock.call(mock_sc.return_value, devices_1[0], 18, 28, 'user', 'pass'), @@ -95,13 +96,13 @@ class TestHoneywell(unittest.TestCase): mock_sc.side_effect = somecomfort.AuthError result = honeywell.setup_platform(hass, config, add_entities) - self.assertFalse(result) - self.assertFalse(add_entities.called) + assert not result + assert not add_entities.called mock_sc.side_effect = somecomfort.SomeComfortError result = honeywell.setup_platform(hass, config, add_entities) - self.assertFalse(result) - self.assertFalse(add_entities.called) + assert not result + assert not add_entities.called @mock.patch('somecomfort.SomeComfort') @mock.patch('homeassistant.components.climate.' @@ -137,8 +138,7 @@ class TestHoneywell(unittest.TestCase): mock_sc.return_value = mock.MagicMock(locations_by_id=locations) hass = mock.MagicMock() add_entities = mock.MagicMock() - self.assertEqual(True, - honeywell.setup_platform(hass, config, add_entities)) + assert honeywell.setup_platform(hass, config, add_entities) is True return mock_ht.call_args_list, mock_sc @@ -147,29 +147,28 @@ class TestHoneywell(unittest.TestCase): result, client = self._test_us_filtered_devices( dev=mock.sentinel.loc1dev1) devices = [x[0][1].deviceid for x in result] - self.assertEqual([mock.sentinel.loc1dev1], devices) + assert [mock.sentinel.loc1dev1] == devices def test_us_filtered_thermostat_2(self): """Test for US filtered location.""" result, client = self._test_us_filtered_devices( dev=mock.sentinel.loc2dev1) devices = [x[0][1].deviceid for x in result] - self.assertEqual([mock.sentinel.loc2dev1], devices) + assert [mock.sentinel.loc2dev1] == devices def test_us_filtered_location_1(self): """Test for US filtered locations.""" result, client = self._test_us_filtered_devices( loc=mock.sentinel.loc1) devices = [x[0][1].deviceid for x in result] - self.assertEqual([mock.sentinel.loc1dev1, - mock.sentinel.loc1dev2], devices) + assert [mock.sentinel.loc1dev1, mock.sentinel.loc1dev2] == devices def test_us_filtered_location_2(self): """Test for US filtered locations.""" result, client = self._test_us_filtered_devices( loc=mock.sentinel.loc2) devices = [x[0][1].deviceid for x in result] - self.assertEqual([mock.sentinel.loc2dev1], devices) + assert [mock.sentinel.loc2dev1] == devices @mock.patch('evohomeclient.EvohomeClient') @mock.patch('homeassistant.components.climate.honeywell.' @@ -186,19 +185,17 @@ class TestHoneywell(unittest.TestCase): {'id': 'foo'}, {'id': 'bar'}] hass = mock.MagicMock() add_entities = mock.MagicMock() - self.assertTrue(honeywell.setup_platform(hass, config, add_entities)) - self.assertEqual(mock_evo.call_count, 1) - self.assertEqual(mock_evo.call_args, mock.call('user', 'pass')) - self.assertEqual(mock_evo.return_value.temperatures.call_count, 1) - self.assertEqual( - mock_evo.return_value.temperatures.call_args, + assert honeywell.setup_platform(hass, config, add_entities) + assert mock_evo.call_count == 1 + assert mock_evo.call_args == mock.call('user', 'pass') + assert mock_evo.return_value.temperatures.call_count == 1 + assert mock_evo.return_value.temperatures.call_args == \ mock.call(force_refresh=True) - ) mock_round.assert_has_calls([ mock.call(mock_evo.return_value, 'foo', True, 20.0), mock.call(mock_evo.return_value, 'bar', False, 20.0), ]) - self.assertEqual(2, add_entities.call_count) + assert 2 == add_entities.call_count @mock.patch('evohomeclient.EvohomeClient') @mock.patch('homeassistant.components.climate.honeywell.' @@ -218,7 +215,7 @@ class TestHoneywell(unittest.TestCase): hass = mock.MagicMock() add_entities = mock.MagicMock() - self.assertTrue(honeywell.setup_platform(hass, config, add_entities)) + assert honeywell.setup_platform(hass, config, add_entities) mock_round.assert_has_calls([ mock.call(mock_evo.return_value, 'foo', True, 16), mock.call(mock_evo.return_value, 'bar', False, 16), @@ -236,7 +233,7 @@ class TestHoneywell(unittest.TestCase): honeywell.CONF_REGION: 'eu', } - with self.assertRaises(vol.Invalid): + with pytest.raises(vol.Invalid): honeywell.PLATFORM_SCHEMA(config) @mock.patch('evohomeclient.EvohomeClient') @@ -253,7 +250,7 @@ class TestHoneywell(unittest.TestCase): mock_evo.return_value.temperatures.side_effect = socket.error add_entities = mock.MagicMock() hass = mock.MagicMock() - self.assertFalse(honeywell.setup_platform(hass, config, add_entities)) + assert not honeywell.setup_platform(hass, config, add_entities) class TestHoneywellRound(unittest.TestCase): @@ -282,53 +279,47 @@ class TestHoneywellRound(unittest.TestCase): def test_attributes(self): """Test the attributes.""" - self.assertEqual('House', self.round1.name) - self.assertEqual(TEMP_CELSIUS, self.round1.temperature_unit) - self.assertEqual(20, self.round1.current_temperature) - self.assertEqual(21, self.round1.target_temperature) - self.assertFalse(self.round1.is_away_mode_on) + assert 'House' == self.round1.name + assert TEMP_CELSIUS == self.round1.temperature_unit + assert 20 == self.round1.current_temperature + assert 21 == self.round1.target_temperature + assert not self.round1.is_away_mode_on - self.assertEqual('Hot Water', self.round2.name) - self.assertEqual(TEMP_CELSIUS, self.round2.temperature_unit) - self.assertEqual(21, self.round2.current_temperature) - self.assertEqual(None, self.round2.target_temperature) - self.assertFalse(self.round2.is_away_mode_on) + assert 'Hot Water' == self.round2.name + assert TEMP_CELSIUS == self.round2.temperature_unit + assert 21 == self.round2.current_temperature + assert self.round2.target_temperature is None + assert not self.round2.is_away_mode_on def test_away_mode(self): """Test setting the away mode.""" - self.assertFalse(self.round1.is_away_mode_on) + assert not self.round1.is_away_mode_on self.round1.turn_away_mode_on() - self.assertTrue(self.round1.is_away_mode_on) - self.assertEqual(self.device.set_temperature.call_count, 1) - self.assertEqual( - self.device.set_temperature.call_args, mock.call('House', 16) - ) + assert self.round1.is_away_mode_on + assert self.device.set_temperature.call_count == 1 + assert self.device.set_temperature.call_args == mock.call('House', 16) self.device.set_temperature.reset_mock() self.round1.turn_away_mode_off() - self.assertFalse(self.round1.is_away_mode_on) - self.assertEqual(self.device.cancel_temp_override.call_count, 1) - self.assertEqual( - self.device.cancel_temp_override.call_args, mock.call('House') - ) + assert not self.round1.is_away_mode_on + assert self.device.cancel_temp_override.call_count == 1 + assert self.device.cancel_temp_override.call_args == mock.call('House') def test_set_temperature(self): """Test setting the temperature.""" self.round1.set_temperature(temperature=25) - self.assertEqual(self.device.set_temperature.call_count, 1) - self.assertEqual( - self.device.set_temperature.call_args, mock.call('House', 25) - ) + assert self.device.set_temperature.call_count == 1 + assert self.device.set_temperature.call_args == mock.call('House', 25) def test_set_operation_mode(self) -> None: """Test setting the system operation.""" self.round1.set_operation_mode('cool') - self.assertEqual('cool', self.round1.current_operation) - self.assertEqual('cool', self.device.system_mode) + assert 'cool' == self.round1.current_operation + assert 'cool' == self.device.system_mode self.round1.set_operation_mode('heat') - self.assertEqual('heat', self.round1.current_operation) - self.assertEqual('heat', self.device.system_mode) + assert 'heat' == self.round1.current_operation + assert 'heat' == self.device.system_mode class TestHoneywellUS(unittest.TestCase): @@ -356,41 +347,41 @@ class TestHoneywellUS(unittest.TestCase): def test_properties(self): """Test the properties.""" - self.assertTrue(self.honeywell.is_fan_on) - self.assertEqual('test', self.honeywell.name) - self.assertEqual(72, self.honeywell.current_temperature) + assert self.honeywell.is_fan_on + assert 'test' == self.honeywell.name + assert 72 == self.honeywell.current_temperature def test_unit_of_measurement(self): """Test the unit of measurement.""" - self.assertEqual(TEMP_FAHRENHEIT, self.honeywell.temperature_unit) + assert TEMP_FAHRENHEIT == self.honeywell.temperature_unit self.device.temperature_unit = 'C' - self.assertEqual(TEMP_CELSIUS, self.honeywell.temperature_unit) + assert TEMP_CELSIUS == self.honeywell.temperature_unit def test_target_temp(self): """Test the target temperature.""" - self.assertEqual(65, self.honeywell.target_temperature) + assert 65 == self.honeywell.target_temperature self.device.system_mode = 'cool' - self.assertEqual(78, self.honeywell.target_temperature) + assert 78 == self.honeywell.target_temperature def test_set_temp(self): """Test setting the temperature.""" self.honeywell.set_temperature(temperature=70) - self.assertEqual(70, self.device.setpoint_heat) - self.assertEqual(70, self.honeywell.target_temperature) + assert 70 == self.device.setpoint_heat + assert 70 == self.honeywell.target_temperature self.device.system_mode = 'cool' - self.assertEqual(78, self.honeywell.target_temperature) + assert 78 == self.honeywell.target_temperature self.honeywell.set_temperature(temperature=74) - self.assertEqual(74, self.device.setpoint_cool) - self.assertEqual(74, self.honeywell.target_temperature) + assert 74 == self.device.setpoint_cool + assert 74 == self.honeywell.target_temperature def test_set_operation_mode(self) -> None: """Test setting the operation mode.""" self.honeywell.set_operation_mode('cool') - self.assertEqual('cool', self.device.system_mode) + assert 'cool' == self.device.system_mode self.honeywell.set_operation_mode('heat') - self.assertEqual('heat', self.device.system_mode) + assert 'heat' == self.device.system_mode def test_set_temp_fail(self): """Test if setting the temperature fails.""" @@ -407,10 +398,10 @@ class TestHoneywellUS(unittest.TestCase): ATTR_FAN_LIST: somecomfort.FAN_MODES, ATTR_OPERATION_LIST: somecomfort.SYSTEM_MODES, } - self.assertEqual(expected, self.honeywell.device_state_attributes) + assert expected == self.honeywell.device_state_attributes expected['fan'] = 'idle' self.device.fan_running = False - self.assertEqual(expected, self.honeywell.device_state_attributes) + assert expected == self.honeywell.device_state_attributes def test_with_no_fan(self): """Test if there is on fan.""" @@ -423,24 +414,24 @@ class TestHoneywellUS(unittest.TestCase): ATTR_FAN_LIST: somecomfort.FAN_MODES, ATTR_OPERATION_LIST: somecomfort.SYSTEM_MODES, } - self.assertEqual(expected, self.honeywell.device_state_attributes) + assert expected == self.honeywell.device_state_attributes def test_heat_away_mode(self): """Test setting the heat away mode.""" self.honeywell.set_operation_mode('heat') - self.assertFalse(self.honeywell.is_away_mode_on) + assert not self.honeywell.is_away_mode_on self.honeywell.turn_away_mode_on() - self.assertTrue(self.honeywell.is_away_mode_on) - self.assertEqual(self.device.setpoint_heat, self.heat_away_temp) - self.assertEqual(self.device.hold_heat, True) + assert self.honeywell.is_away_mode_on + assert self.device.setpoint_heat == self.heat_away_temp + assert self.device.hold_heat is True self.honeywell.turn_away_mode_off() - self.assertFalse(self.honeywell.is_away_mode_on) - self.assertEqual(self.device.hold_heat, False) + assert not self.honeywell.is_away_mode_on + assert self.device.hold_heat is False @mock.patch('somecomfort.SomeComfort') def test_retry(self, test_somecomfort): """Test retry connection.""" old_device = self.honeywell._device self.honeywell._retry() - self.assertEqual(self.honeywell._device, old_device) + assert self.honeywell._device == old_device diff --git a/tests/components/climate/test_melissa.py b/tests/components/climate/test_melissa.py index 563f74383..538e642cd 100644 --- a/tests/components/climate/test_melissa.py +++ b/tests/components/climate/test_melissa.py @@ -84,133 +84,129 @@ class TestMelissa(unittest.TestCase): def test_get_name(self): """Test name property.""" - self.assertEqual("Melissa 12345678", self.thermostat.name) + assert "Melissa 12345678" == self.thermostat.name def test_is_on(self): """Test name property.""" - self.assertTrue(self.thermostat.is_on) + assert self.thermostat.is_on self.thermostat._cur_settings = None - self.assertFalse(self.thermostat.is_on) + assert not self.thermostat.is_on def test_current_fan_mode(self): """Test current_fan_mode property.""" self.thermostat.update() - self.assertEqual(SPEED_LOW, self.thermostat.current_fan_mode) + assert SPEED_LOW == self.thermostat.current_fan_mode self.thermostat._cur_settings = None - self.assertEqual(None, self.thermostat.current_fan_mode) + assert self.thermostat.current_fan_mode is None def test_current_temperature(self): """Test current temperature.""" - self.assertEqual(27.4, self.thermostat.current_temperature) + assert 27.4 == self.thermostat.current_temperature def test_current_temperature_no_data(self): """Test current temperature without data.""" self.thermostat._data = None - self.assertIsNone(self.thermostat.current_temperature) + assert self.thermostat.current_temperature is None def test_target_temperature_step(self): """Test current target_temperature_step.""" - self.assertEqual(1, self.thermostat.target_temperature_step) + assert 1 == self.thermostat.target_temperature_step def test_current_operation(self): """Test current operation.""" self.thermostat.update() - self.assertEqual(self.thermostat.current_operation, STATE_HEAT) + assert self.thermostat.current_operation == STATE_HEAT self.thermostat._cur_settings = None - self.assertEqual(None, self.thermostat.current_operation) + assert self.thermostat.current_operation is None def test_operation_list(self): """Test the operation list.""" - self.assertEqual( - [STATE_COOL, STATE_DRY, STATE_FAN_ONLY, STATE_HEAT], + assert [STATE_COOL, STATE_DRY, STATE_FAN_ONLY, STATE_HEAT] == \ self.thermostat.operation_list - ) def test_fan_list(self): """Test the fan list.""" - self.assertEqual( - [STATE_AUTO, SPEED_HIGH, SPEED_LOW, SPEED_MEDIUM], + assert [STATE_AUTO, SPEED_HIGH, SPEED_LOW, SPEED_MEDIUM] == \ self.thermostat.fan_list - ) def test_target_temperature(self): """Test target temperature.""" - self.assertEqual(16, self.thermostat.target_temperature) + assert 16 == self.thermostat.target_temperature self.thermostat._cur_settings = None - self.assertEqual(None, self.thermostat.target_temperature) + assert self.thermostat.target_temperature is None def test_state(self): """Test state.""" - self.assertEqual(STATE_ON, self.thermostat.state) + assert STATE_ON == self.thermostat.state self.thermostat._cur_settings = None - self.assertEqual(None, self.thermostat.state) + assert self.thermostat.state is None def test_temperature_unit(self): """Test temperature unit.""" - self.assertEqual(TEMP_CELSIUS, self.thermostat.temperature_unit) + assert TEMP_CELSIUS == self.thermostat.temperature_unit def test_min_temp(self): """Test min temp.""" - self.assertEqual(16, self.thermostat.min_temp) + assert 16 == self.thermostat.min_temp def test_max_temp(self): """Test max temp.""" - self.assertEqual(30, self.thermostat.max_temp) + assert 30 == self.thermostat.max_temp def test_supported_features(self): """Test supported_features property.""" features = (SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE | SUPPORT_ON_OFF | SUPPORT_FAN_MODE) - self.assertEqual(features, self.thermostat.supported_features) + assert features == self.thermostat.supported_features def test_set_temperature(self): """Test set_temperature.""" self.api.send.return_value = True self.thermostat.update() self.thermostat.set_temperature(**{ATTR_TEMPERATURE: 25}) - self.assertEqual(25, self.thermostat.target_temperature) + assert 25 == self.thermostat.target_temperature def test_fan_mode(self): """Test set_fan_mode.""" self.api.send.return_value = True self.thermostat.set_fan_mode(SPEED_HIGH) - self.assertEqual(SPEED_HIGH, self.thermostat.current_fan_mode) + assert SPEED_HIGH == self.thermostat.current_fan_mode def test_set_operation_mode(self): """Test set_operation_mode.""" self.api.send.return_value = True self.thermostat.set_operation_mode(STATE_COOL) - self.assertEqual(STATE_COOL, self.thermostat.current_operation) + assert STATE_COOL == self.thermostat.current_operation def test_turn_on(self): """Test turn_on.""" self.thermostat.turn_on() - self.assertTrue(self.thermostat.state) + assert self.thermostat.state def test_turn_off(self): """Test turn_off.""" self.thermostat.turn_off() - self.assertEqual(STATE_OFF, self.thermostat.state) + assert STATE_OFF == self.thermostat.state def test_send(self): """Test send.""" self.thermostat.update() - self.assertTrue(self.thermostat.send( - {'fan': self.api.FAN_MEDIUM})) - self.assertEqual(SPEED_MEDIUM, self.thermostat.current_fan_mode) + assert self.thermostat.send( + {'fan': self.api.FAN_MEDIUM}) + assert SPEED_MEDIUM == self.thermostat.current_fan_mode self.api.send.return_value = False self.thermostat._cur_settings = None - self.assertFalse(self.thermostat.send({ - 'fan': self.api.FAN_LOW})) - self.assertNotEqual(SPEED_LOW, self.thermostat.current_fan_mode) - self.assertIsNone(self.thermostat._cur_settings) + assert not self.thermostat.send({ + 'fan': self.api.FAN_LOW}) + assert SPEED_LOW != self.thermostat.current_fan_mode + assert self.thermostat._cur_settings is None @mock.patch('homeassistant.components.climate.melissa._LOGGER.warning') def test_update(self, mocked_warning): """Test update.""" self.thermostat.update() - self.assertEqual(SPEED_LOW, self.thermostat.current_fan_mode) - self.assertEqual(STATE_HEAT, self.thermostat.current_operation) + assert SPEED_LOW == self.thermostat.current_fan_mode + assert STATE_HEAT == self.thermostat.current_operation self.thermostat._api.status.side_effect = KeyError('boom') self.thermostat.update() mocked_warning.assert_called_once_with( @@ -218,37 +214,34 @@ class TestMelissa(unittest.TestCase): def test_melissa_state_to_hass(self): """Test for translate melissa states to hass.""" - self.assertEqual(STATE_OFF, self.thermostat.melissa_state_to_hass(0)) - self.assertEqual(STATE_ON, self.thermostat.melissa_state_to_hass(1)) - self.assertEqual(STATE_IDLE, self.thermostat.melissa_state_to_hass(2)) - self.assertEqual(None, - self.thermostat.melissa_state_to_hass(3)) + assert STATE_OFF == self.thermostat.melissa_state_to_hass(0) + assert STATE_ON == self.thermostat.melissa_state_to_hass(1) + assert STATE_IDLE == self.thermostat.melissa_state_to_hass(2) + assert self.thermostat.melissa_state_to_hass(3) is None def test_melissa_op_to_hass(self): """Test for translate melissa operations to hass.""" - self.assertEqual(STATE_FAN_ONLY, self.thermostat.melissa_op_to_hass(1)) - self.assertEqual(STATE_HEAT, self.thermostat.melissa_op_to_hass(2)) - self.assertEqual(STATE_COOL, self.thermostat.melissa_op_to_hass(3)) - self.assertEqual(STATE_DRY, self.thermostat.melissa_op_to_hass(4)) - self.assertEqual( - None, self.thermostat.melissa_op_to_hass(5)) + assert STATE_FAN_ONLY == self.thermostat.melissa_op_to_hass(1) + assert STATE_HEAT == self.thermostat.melissa_op_to_hass(2) + assert STATE_COOL == self.thermostat.melissa_op_to_hass(3) + assert STATE_DRY == self.thermostat.melissa_op_to_hass(4) + assert self.thermostat.melissa_op_to_hass(5) is None def test_melissa_fan_to_hass(self): """Test for translate melissa fan state to hass.""" - self.assertEqual(STATE_AUTO, self.thermostat.melissa_fan_to_hass(0)) - self.assertEqual(SPEED_LOW, self.thermostat.melissa_fan_to_hass(1)) - self.assertEqual(SPEED_MEDIUM, self.thermostat.melissa_fan_to_hass(2)) - self.assertEqual(SPEED_HIGH, self.thermostat.melissa_fan_to_hass(3)) - self.assertEqual(None, self.thermostat.melissa_fan_to_hass(4)) + assert STATE_AUTO == self.thermostat.melissa_fan_to_hass(0) + assert SPEED_LOW == self.thermostat.melissa_fan_to_hass(1) + assert SPEED_MEDIUM == self.thermostat.melissa_fan_to_hass(2) + assert SPEED_HIGH == self.thermostat.melissa_fan_to_hass(3) + assert self.thermostat.melissa_fan_to_hass(4) is None @mock.patch('homeassistant.components.climate.melissa._LOGGER.warning') def test_hass_mode_to_melissa(self, mocked_warning): """Test for hass operations to melssa.""" - self.assertEqual( - 1, self.thermostat.hass_mode_to_melissa(STATE_FAN_ONLY)) - self.assertEqual(2, self.thermostat.hass_mode_to_melissa(STATE_HEAT)) - self.assertEqual(3, self.thermostat.hass_mode_to_melissa(STATE_COOL)) - self.assertEqual(4, self.thermostat.hass_mode_to_melissa(STATE_DRY)) + assert 1 == self.thermostat.hass_mode_to_melissa(STATE_FAN_ONLY) + assert 2 == self.thermostat.hass_mode_to_melissa(STATE_HEAT) + assert 3 == self.thermostat.hass_mode_to_melissa(STATE_COOL) + assert 4 == self.thermostat.hass_mode_to_melissa(STATE_DRY) self.thermostat.hass_mode_to_melissa("test") mocked_warning.assert_called_once_with( "Melissa have no setting for %s mode", "test") @@ -256,10 +249,10 @@ class TestMelissa(unittest.TestCase): @mock.patch('homeassistant.components.climate.melissa._LOGGER.warning') def test_hass_fan_to_melissa(self, mocked_warning): """Test for translate melissa states to hass.""" - self.assertEqual(0, self.thermostat.hass_fan_to_melissa(STATE_AUTO)) - self.assertEqual(1, self.thermostat.hass_fan_to_melissa(SPEED_LOW)) - self.assertEqual(2, self.thermostat.hass_fan_to_melissa(SPEED_MEDIUM)) - self.assertEqual(3, self.thermostat.hass_fan_to_melissa(SPEED_HIGH)) + assert 0 == self.thermostat.hass_fan_to_melissa(STATE_AUTO) + assert 1 == self.thermostat.hass_fan_to_melissa(SPEED_LOW) + assert 2 == self.thermostat.hass_fan_to_melissa(SPEED_MEDIUM) + assert 3 == self.thermostat.hass_fan_to_melissa(SPEED_HIGH) self.thermostat.hass_fan_to_melissa("test") mocked_warning.assert_called_once_with( "Melissa have no setting for %s fan mode", "test") diff --git a/tests/components/climate/test_mqtt.py b/tests/components/climate/test_mqtt.py index 16fe0a663..61b481ed4 100644 --- a/tests/components/climate/test_mqtt.py +++ b/tests/components/climate/test_mqtt.py @@ -52,12 +52,12 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(21, state.attributes.get('temperature')) - self.assertEqual("low", state.attributes.get('fan_mode')) - self.assertEqual("off", state.attributes.get('swing_mode')) - self.assertEqual("off", state.attributes.get('operation_mode')) - self.assertEqual(DEFAULT_MIN_TEMP, state.attributes.get('min_temp')) - self.assertEqual(DEFAULT_MAX_TEMP, state.attributes.get('max_temp')) + assert 21 == state.attributes.get('temperature') + assert "low" == state.attributes.get('fan_mode') + assert "off" == state.attributes.get('swing_mode') + assert "off" == state.attributes.get('operation_mode') + assert DEFAULT_MIN_TEMP == state.attributes.get('min_temp') + assert DEFAULT_MAX_TEMP == state.attributes.get('max_temp') def test_supported_features(self): """Test the supported_features.""" @@ -68,7 +68,7 @@ class TestMQTTClimate(unittest.TestCase): SUPPORT_SWING_MODE | SUPPORT_FAN_MODE | SUPPORT_AWAY_MODE | SUPPORT_HOLD_MODE | SUPPORT_AUX_HEAT) - self.assertEqual(state.attributes.get("supported_features"), support) + assert state.attributes.get("supported_features") == support def test_get_operation_modes(self): """Test that the operation list returns the correct modes.""" @@ -76,10 +76,10 @@ class TestMQTTClimate(unittest.TestCase): state = self.hass.states.get(ENTITY_CLIMATE) modes = state.attributes.get('operation_list') - self.assertEqual([ + assert [ climate.STATE_AUTO, STATE_OFF, climate.STATE_COOL, climate.STATE_HEAT, climate.STATE_DRY, climate.STATE_FAN_ONLY - ], modes) + ] == modes def test_set_operation_bad_attr_and_state(self): """Test setting operation mode without required attribute. @@ -89,26 +89,26 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("off", state.attributes.get('operation_mode')) - self.assertEqual("off", state.state) + assert "off" == state.attributes.get('operation_mode') + assert "off" == state.state common.set_operation_mode(self.hass, None, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("off", state.attributes.get('operation_mode')) - self.assertEqual("off", state.state) + assert "off" == state.attributes.get('operation_mode') + assert "off" == state.state def test_set_operation(self): """Test setting of new operation mode.""" assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("off", state.attributes.get('operation_mode')) - self.assertEqual("off", state.state) + assert "off" == state.attributes.get('operation_mode') + assert "off" == state.state common.set_operation_mode(self.hass, "cool", ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("cool", state.attributes.get('operation_mode')) - self.assertEqual("cool", state.state) + assert "cool" == state.attributes.get('operation_mode') + assert "cool" == state.state self.mock_publish.async_publish.assert_called_once_with( 'mode-topic', 'cool', 0, False) @@ -119,26 +119,26 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, config) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('operation_mode')) - self.assertEqual("unknown", state.state) + assert state.attributes.get('operation_mode') is None + assert "unknown" == state.state common.set_operation_mode(self.hass, "cool", ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('operation_mode')) - self.assertEqual("unknown", state.state) + assert state.attributes.get('operation_mode') is None + assert "unknown" == state.state fire_mqtt_message(self.hass, 'mode-state', 'cool') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("cool", state.attributes.get('operation_mode')) - self.assertEqual("cool", state.state) + assert "cool" == state.attributes.get('operation_mode') + assert "cool" == state.state fire_mqtt_message(self.hass, 'mode-state', 'bogus mode') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("cool", state.attributes.get('operation_mode')) - self.assertEqual("cool", state.state) + assert "cool" == state.attributes.get('operation_mode') + assert "cool" == state.state def test_set_operation_with_power_command(self): """Test setting of new operation mode with power command enabled.""" @@ -147,13 +147,13 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, config) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("off", state.attributes.get('operation_mode')) - self.assertEqual("off", state.state) + assert "off" == state.attributes.get('operation_mode') + assert "off" == state.state common.set_operation_mode(self.hass, "on", ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("on", state.attributes.get('operation_mode')) - self.assertEqual("on", state.state) + assert "on" == state.attributes.get('operation_mode') + assert "on" == state.state self.mock_publish.async_publish.assert_has_calls([ unittest.mock.call('power-command', 'ON', 0, False), unittest.mock.call('mode-topic', 'on', 0, False) @@ -163,8 +163,8 @@ class TestMQTTClimate(unittest.TestCase): common.set_operation_mode(self.hass, "off", ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("off", state.attributes.get('operation_mode')) - self.assertEqual("off", state.state) + assert "off" == state.attributes.get('operation_mode') + assert "off" == state.state self.mock_publish.async_publish.assert_has_calls([ unittest.mock.call('power-command', 'OFF', 0, False), unittest.mock.call('mode-topic', 'off', 0, False) @@ -176,11 +176,11 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("low", state.attributes.get('fan_mode')) + assert "low" == state.attributes.get('fan_mode') common.set_fan_mode(self.hass, None, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("low", state.attributes.get('fan_mode')) + assert "low" == state.attributes.get('fan_mode') def test_set_fan_mode_pessimistic(self): """Test setting of new fan mode in pessimistic mode.""" @@ -189,46 +189,46 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, config) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('fan_mode')) + assert state.attributes.get('fan_mode') is None common.set_fan_mode(self.hass, 'high', ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('fan_mode')) + assert state.attributes.get('fan_mode') is None fire_mqtt_message(self.hass, 'fan-state', 'high') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('high', state.attributes.get('fan_mode')) + assert 'high' == state.attributes.get('fan_mode') fire_mqtt_message(self.hass, 'fan-state', 'bogus mode') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('high', state.attributes.get('fan_mode')) + assert 'high' == state.attributes.get('fan_mode') def test_set_fan_mode(self): """Test setting of new fan mode.""" assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("low", state.attributes.get('fan_mode')) + assert "low" == state.attributes.get('fan_mode') common.set_fan_mode(self.hass, 'high', ENTITY_CLIMATE) self.hass.block_till_done() self.mock_publish.async_publish.assert_called_once_with( 'fan-mode-topic', 'high', 0, False) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('high', state.attributes.get('fan_mode')) + assert 'high' == state.attributes.get('fan_mode') def test_set_swing_mode_bad_attr(self): """Test setting swing mode without required attribute.""" assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("off", state.attributes.get('swing_mode')) + assert "off" == state.attributes.get('swing_mode') common.set_swing_mode(self.hass, None, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("off", state.attributes.get('swing_mode')) + assert "off" == state.attributes.get('swing_mode') def test_set_swing_pessimistic(self): """Test setting swing mode in pessimistic mode.""" @@ -237,46 +237,46 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, config) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('swing_mode')) + assert state.attributes.get('swing_mode') is None common.set_swing_mode(self.hass, 'on', ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('swing_mode')) + assert state.attributes.get('swing_mode') is None fire_mqtt_message(self.hass, 'swing-state', 'on') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("on", state.attributes.get('swing_mode')) + assert "on" == state.attributes.get('swing_mode') fire_mqtt_message(self.hass, 'swing-state', 'bogus state') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("on", state.attributes.get('swing_mode')) + assert "on" == state.attributes.get('swing_mode') def test_set_swing(self): """Test setting of new swing mode.""" assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("off", state.attributes.get('swing_mode')) + assert "off" == state.attributes.get('swing_mode') common.set_swing_mode(self.hass, 'on', ENTITY_CLIMATE) self.hass.block_till_done() self.mock_publish.async_publish.assert_called_once_with( 'swing-mode-topic', 'on', 0, False) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("on", state.attributes.get('swing_mode')) + assert "on" == state.attributes.get('swing_mode') def test_set_target_temperature(self): """Test setting the target temperature.""" assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(21, state.attributes.get('temperature')) + assert 21 == state.attributes.get('temperature') common.set_operation_mode(self.hass, 'heat', ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('heat', state.attributes.get('operation_mode')) + assert 'heat' == state.attributes.get('operation_mode') self.mock_publish.async_publish.assert_called_once_with( 'mode-topic', 'heat', 0, False) self.mock_publish.async_publish.reset_mock() @@ -284,7 +284,7 @@ class TestMQTTClimate(unittest.TestCase): entity_id=ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(47, state.attributes.get('temperature')) + assert 47 == state.attributes.get('temperature') self.mock_publish.async_publish.assert_called_once_with( 'temperature-topic', 47, 0, False) @@ -295,8 +295,8 @@ class TestMQTTClimate(unittest.TestCase): entity_id=ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('cool', state.attributes.get('operation_mode')) - self.assertEqual(21, state.attributes.get('temperature')) + assert 'cool' == state.attributes.get('operation_mode') + assert 21 == state.attributes.get('temperature') self.mock_publish.async_publish.assert_has_calls([ unittest.mock.call('mode-topic', 'cool', 0, False), unittest.mock.call('temperature-topic', 21, 0, False) @@ -310,24 +310,24 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, config) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('temperature')) + assert state.attributes.get('temperature') is None common.set_operation_mode(self.hass, 'heat', ENTITY_CLIMATE) self.hass.block_till_done() common.set_temperature(self.hass, temperature=47, entity_id=ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('temperature')) + assert state.attributes.get('temperature') is None fire_mqtt_message(self.hass, 'temperature-state', '1701') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(1701, state.attributes.get('temperature')) + assert 1701 == state.attributes.get('temperature') fire_mqtt_message(self.hass, 'temperature-state', 'not a number') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(1701, state.attributes.get('temperature')) + assert 1701 == state.attributes.get('temperature') def test_receive_mqtt_temperature(self): """Test getting the current temperature via MQTT.""" @@ -339,7 +339,7 @@ class TestMQTTClimate(unittest.TestCase): fire_mqtt_message(self.hass, 'current_temperature', '47') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(47, state.attributes.get('current_temperature')) + assert 47 == state.attributes.get('current_temperature') def test_set_away_mode_pessimistic(self): """Test setting of the away mode.""" @@ -348,27 +348,27 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, config) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') common.set_away_mode(self.hass, True, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') fire_mqtt_message(self.hass, 'away-state', 'ON') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('away_mode')) + assert 'on' == state.attributes.get('away_mode') fire_mqtt_message(self.hass, 'away-state', 'OFF') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') fire_mqtt_message(self.hass, 'away-state', 'nonsense') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') def test_set_away_mode(self): """Test setting of the away mode.""" @@ -379,21 +379,21 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, config) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') common.set_away_mode(self.hass, True, ENTITY_CLIMATE) self.hass.block_till_done() self.mock_publish.async_publish.assert_called_once_with( 'away-mode-topic', 'AN', 0, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('away_mode')) + assert 'on' == state.attributes.get('away_mode') common.set_away_mode(self.hass, False, ENTITY_CLIMATE) self.hass.block_till_done() self.mock_publish.async_publish.assert_called_once_with( 'away-mode-topic', 'AUS', 0, False) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') def test_set_hold_pessimistic(self): """Test setting the hold mode in pessimistic mode.""" @@ -402,43 +402,43 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, config) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('hold_mode')) + assert state.attributes.get('hold_mode') is None common.set_hold_mode(self.hass, 'on', ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('hold_mode')) + assert state.attributes.get('hold_mode') is None fire_mqtt_message(self.hass, 'hold-state', 'on') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('hold_mode')) + assert 'on' == state.attributes.get('hold_mode') fire_mqtt_message(self.hass, 'hold-state', 'off') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('hold_mode')) + assert 'off' == state.attributes.get('hold_mode') def test_set_hold(self): """Test setting the hold mode.""" assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('hold_mode')) + assert state.attributes.get('hold_mode') is None common.set_hold_mode(self.hass, 'on', ENTITY_CLIMATE) self.hass.block_till_done() self.mock_publish.async_publish.assert_called_once_with( 'hold-topic', 'on', 0, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('hold_mode')) + assert 'on' == state.attributes.get('hold_mode') common.set_hold_mode(self.hass, 'off', ENTITY_CLIMATE) self.hass.block_till_done() self.mock_publish.async_publish.assert_called_once_with( 'hold-topic', 'off', 0, False) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('hold_mode')) + assert 'off' == state.attributes.get('hold_mode') def test_set_aux_pessimistic(self): """Test setting of the aux heating in pessimistic mode.""" @@ -447,48 +447,48 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, config) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 'off' == state.attributes.get('aux_heat') common.set_aux_heat(self.hass, True, ENTITY_CLIMATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 'off' == state.attributes.get('aux_heat') fire_mqtt_message(self.hass, 'aux-state', 'ON') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('aux_heat')) + assert 'on' == state.attributes.get('aux_heat') fire_mqtt_message(self.hass, 'aux-state', 'OFF') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 'off' == state.attributes.get('aux_heat') fire_mqtt_message(self.hass, 'aux-state', 'nonsense') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 'off' == state.attributes.get('aux_heat') def test_set_aux(self): """Test setting of the aux heating.""" assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 'off' == state.attributes.get('aux_heat') common.set_aux_heat(self.hass, True, ENTITY_CLIMATE) self.hass.block_till_done() self.mock_publish.async_publish.assert_called_once_with( 'aux-topic', 'ON', 0, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('aux_heat')) + assert 'on' == state.attributes.get('aux_heat') common.set_aux_heat(self.hass, False, ENTITY_CLIMATE) self.hass.block_till_done() self.mock_publish.async_publish.assert_called_once_with( 'aux-topic', 'OFF', 0, False) state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 'off' == state.attributes.get('aux_heat') def test_custom_availability_payload(self): """Test availability by custom payload with defined topic.""" @@ -500,19 +500,19 @@ class TestMQTTClimate(unittest.TestCase): assert setup_component(self.hass, climate.DOMAIN, config) state = self.hass.states.get('climate.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'good') self.hass.block_till_done() state = self.hass.states.get('climate.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'nogood') self.hass.block_till_done() state = self.hass.states.get('climate.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def test_set_with_templates(self): """Test setting of new fan mode in pessimistic mode.""" @@ -539,32 +539,32 @@ class TestMQTTClimate(unittest.TestCase): # Operation Mode state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(None, state.attributes.get('operation_mode')) + assert state.attributes.get('operation_mode') is None fire_mqtt_message(self.hass, 'mode-state', '"cool"') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("cool", state.attributes.get('operation_mode')) + assert "cool" == state.attributes.get('operation_mode') # Fan Mode - self.assertEqual(None, state.attributes.get('fan_mode')) + assert state.attributes.get('fan_mode') is None fire_mqtt_message(self.hass, 'fan-state', '"high"') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('high', state.attributes.get('fan_mode')) + assert 'high' == state.attributes.get('fan_mode') # Swing Mode - self.assertEqual(None, state.attributes.get('swing_mode')) + assert state.attributes.get('swing_mode') is None fire_mqtt_message(self.hass, 'swing-state', '"on"') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual("on", state.attributes.get('swing_mode')) + assert "on" == state.attributes.get('swing_mode') # Temperature - with valid value - self.assertEqual(None, state.attributes.get('temperature')) + assert state.attributes.get('temperature') is None fire_mqtt_message(self.hass, 'temperature-state', '"1031"') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(1031, state.attributes.get('temperature')) + assert 1031 == state.attributes.get('temperature') # Temperature - with invalid value with self.assertLogs(level='ERROR') as log: @@ -572,60 +572,58 @@ class TestMQTTClimate(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) # make sure, the invalid value gets logged... - self.assertEqual(len(log.output), 1) - self.assertEqual(len(log.records), 1) - self.assertIn( - "Could not parse temperature from -INVALID-", + assert len(log.output) == 1 + assert len(log.records) == 1 + assert "Could not parse temperature from -INVALID-" in \ log.output[0] - ) # ... but the actual value stays unchanged. - self.assertEqual(1031, state.attributes.get('temperature')) + assert 1031 == state.attributes.get('temperature') # Away Mode - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') fire_mqtt_message(self.hass, 'away-state', '"ON"') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('away_mode')) + assert 'on' == state.attributes.get('away_mode') # Away Mode with JSON values fire_mqtt_message(self.hass, 'away-state', 'false') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') fire_mqtt_message(self.hass, 'away-state', 'true') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('away_mode')) + assert 'on' == state.attributes.get('away_mode') # Hold Mode - self.assertEqual(None, state.attributes.get('hold_mode')) + assert state.attributes.get('hold_mode') is None fire_mqtt_message(self.hass, 'hold-state', """ { "attribute": "somemode" } """) self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('somemode', state.attributes.get('hold_mode')) + assert 'somemode' == state.attributes.get('hold_mode') # Aux mode - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 'off' == state.attributes.get('aux_heat') fire_mqtt_message(self.hass, 'aux-state', 'switchmeon') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('on', state.attributes.get('aux_heat')) + assert 'on' == state.attributes.get('aux_heat') # anything other than 'switchmeon' should turn Aux mode off fire_mqtt_message(self.hass, 'aux-state', 'somerandomstring') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual('off', state.attributes.get('aux_heat')) + assert 'off' == state.attributes.get('aux_heat') # Current temperature fire_mqtt_message(self.hass, 'current-temperature', '"74656"') self.hass.block_till_done() state = self.hass.states.get(ENTITY_CLIMATE) - self.assertEqual(74656, state.attributes.get('current_temperature')) + assert 74656 == state.attributes.get('current_temperature') def test_min_temp_custom(self): """Test a custom min temp.""" @@ -637,8 +635,8 @@ class TestMQTTClimate(unittest.TestCase): state = self.hass.states.get(ENTITY_CLIMATE) min_temp = state.attributes.get('min_temp') - self.assertIsInstance(min_temp, float) - self.assertEqual(26, state.attributes.get('min_temp')) + assert isinstance(min_temp, float) + assert 26 == state.attributes.get('min_temp') def test_max_temp_custom(self): """Test a custom max temp.""" @@ -650,8 +648,8 @@ class TestMQTTClimate(unittest.TestCase): state = self.hass.states.get(ENTITY_CLIMATE) max_temp = state.attributes.get('max_temp') - self.assertIsInstance(max_temp, float) - self.assertEqual(60, max_temp) + assert isinstance(max_temp, float) + assert 60 == max_temp def test_temp_step_custom(self): """Test a custom temp step.""" @@ -663,8 +661,8 @@ class TestMQTTClimate(unittest.TestCase): state = self.hass.states.get(ENTITY_CLIMATE) temp_step = state.attributes.get('target_temp_step') - self.assertIsInstance(temp_step, float) - self.assertEqual(0.01, temp_step) + assert isinstance(temp_step, float) + assert 0.01 == temp_step async def test_discovery_removal_climate(hass, mqtt_mock, caplog): diff --git a/tests/components/climate/test_nuheat.py b/tests/components/climate/test_nuheat.py index 5b47a5a75..40b0732f6 100644 --- a/tests/components/climate/test_nuheat.py +++ b/tests/components/climate/test_nuheat.py @@ -104,111 +104,105 @@ class TestNuHeat(unittest.TestCase): def test_name(self): """Test name property.""" - self.assertEqual(self.thermostat.name, "Master bathroom") + assert self.thermostat.name == "Master bathroom" def test_icon(self): """Test name property.""" - self.assertEqual(self.thermostat.icon, "mdi:thermometer") + assert self.thermostat.icon == "mdi:thermometer" def test_supported_features(self): """Test name property.""" features = (SUPPORT_TARGET_TEMPERATURE | SUPPORT_HOLD_MODE | SUPPORT_OPERATION_MODE) - self.assertEqual(self.thermostat.supported_features, features) + assert self.thermostat.supported_features == features def test_temperature_unit(self): """Test temperature unit.""" - self.assertEqual(self.thermostat.temperature_unit, TEMP_FAHRENHEIT) + assert self.thermostat.temperature_unit == TEMP_FAHRENHEIT self.thermostat._temperature_unit = "C" - self.assertEqual(self.thermostat.temperature_unit, TEMP_CELSIUS) + assert self.thermostat.temperature_unit == TEMP_CELSIUS def test_current_temperature(self): """Test current temperature.""" - self.assertEqual(self.thermostat.current_temperature, 72) + assert self.thermostat.current_temperature == 72 self.thermostat._temperature_unit = "C" - self.assertEqual(self.thermostat.current_temperature, 22) + assert self.thermostat.current_temperature == 22 def test_current_operation(self): """Test current operation.""" - self.assertEqual(self.thermostat.current_operation, STATE_HEAT) + assert self.thermostat.current_operation == STATE_HEAT self.thermostat._thermostat.heating = False - self.assertEqual(self.thermostat.current_operation, STATE_IDLE) + assert self.thermostat.current_operation == STATE_IDLE def test_min_temp(self): """Test min temp.""" - self.assertEqual(self.thermostat.min_temp, 41) + assert self.thermostat.min_temp == 41 self.thermostat._temperature_unit = "C" - self.assertEqual(self.thermostat.min_temp, 5) + assert self.thermostat.min_temp == 5 def test_max_temp(self): """Test max temp.""" - self.assertEqual(self.thermostat.max_temp, 157) + assert self.thermostat.max_temp == 157 self.thermostat._temperature_unit = "C" - self.assertEqual(self.thermostat.max_temp, 69) + assert self.thermostat.max_temp == 69 def test_target_temperature(self): """Test target temperature.""" - self.assertEqual(self.thermostat.target_temperature, 72) + assert self.thermostat.target_temperature == 72 self.thermostat._temperature_unit = "C" - self.assertEqual(self.thermostat.target_temperature, 22) + assert self.thermostat.target_temperature == 22 def test_current_hold_mode(self): """Test current hold mode.""" self.thermostat._thermostat.schedule_mode = SCHEDULE_RUN - self.assertEqual(self.thermostat.current_hold_mode, nuheat.MODE_AUTO) + assert self.thermostat.current_hold_mode == nuheat.MODE_AUTO self.thermostat._thermostat.schedule_mode = SCHEDULE_HOLD - self.assertEqual( - self.thermostat.current_hold_mode, nuheat.MODE_HOLD_TEMPERATURE) + assert self.thermostat.current_hold_mode == \ + nuheat.MODE_HOLD_TEMPERATURE self.thermostat._thermostat.schedule_mode = SCHEDULE_TEMPORARY_HOLD - self.assertEqual( - self.thermostat.current_hold_mode, nuheat.MODE_TEMPORARY_HOLD) + assert self.thermostat.current_hold_mode == nuheat.MODE_TEMPORARY_HOLD self.thermostat._thermostat.schedule_mode = None - self.assertEqual( - self.thermostat.current_hold_mode, nuheat.MODE_AUTO) + assert self.thermostat.current_hold_mode == nuheat.MODE_AUTO def test_operation_list(self): """Test the operation list.""" - self.assertEqual( - self.thermostat.operation_list, + assert self.thermostat.operation_list == \ [STATE_HEAT, STATE_IDLE] - ) def test_resume_program(self): """Test resume schedule.""" self.thermostat.resume_program() self.thermostat._thermostat.resume_schedule.assert_called_once_with() - self.assertTrue(self.thermostat._force_update) + assert self.thermostat._force_update def test_set_hold_mode(self): """Test set hold mode.""" self.thermostat.set_hold_mode("temperature") - self.assertEqual( - self.thermostat._thermostat.schedule_mode, SCHEDULE_HOLD) - self.assertTrue(self.thermostat._force_update) + assert self.thermostat._thermostat.schedule_mode == SCHEDULE_HOLD + assert self.thermostat._force_update self.thermostat.set_hold_mode("temporary_temperature") - self.assertEqual( - self.thermostat._thermostat.schedule_mode, SCHEDULE_TEMPORARY_HOLD) - self.assertTrue(self.thermostat._force_update) + assert self.thermostat._thermostat.schedule_mode == \ + SCHEDULE_TEMPORARY_HOLD + assert self.thermostat._force_update self.thermostat.set_hold_mode("auto") - self.assertEqual( - self.thermostat._thermostat.schedule_mode, SCHEDULE_RUN) - self.assertTrue(self.thermostat._force_update) + assert self.thermostat._thermostat.schedule_mode == SCHEDULE_RUN + assert self.thermostat._force_update def test_set_temperature(self): """Test set temperature.""" self.thermostat.set_temperature(temperature=85) - self.assertEqual(self.thermostat._thermostat.target_fahrenheit, 85) - self.assertTrue(self.thermostat._force_update) + assert self.thermostat._thermostat.target_fahrenheit == 85 + assert self.thermostat._force_update self.thermostat._temperature_unit = "C" self.thermostat.set_temperature(temperature=23) - self.assertEqual(self.thermostat._thermostat.target_celsius, 23) - self.assertTrue(self.thermostat._force_update) + assert self.thermostat._thermostat.target_celsius == 23 + assert self.thermostat._force_update @patch.object(nuheat.NuHeatThermostat, "_throttled_update") def test_update_without_throttle(self, throttled_update): @@ -216,7 +210,7 @@ class TestNuHeat(unittest.TestCase): self.thermostat._force_update = True self.thermostat.update() throttled_update.assert_called_once_with(no_throttle=True) - self.assertFalse(self.thermostat._force_update) + assert not self.thermostat._force_update @patch.object(nuheat.NuHeatThermostat, "_throttled_update") def test_update_with_throttle(self, throttled_update): @@ -224,7 +218,7 @@ class TestNuHeat(unittest.TestCase): self.thermostat._force_update = False self.thermostat.update() throttled_update.assert_called_once_with() - self.assertFalse(self.thermostat._force_update) + assert not self.thermostat._force_update def test_throttled_update(self): """Test update with throttle.""" diff --git a/tests/components/counter/test_init.py b/tests/components/counter/test_init.py index 929d96d46..78ca72dd1 100644 --- a/tests/components/counter/test_init.py +++ b/tests/components/counter/test_init.py @@ -39,8 +39,7 @@ class TestCounter(unittest.TestCase): ] for cfg in invalid_configs: - self.assertFalse( - setup_component(self.hass, DOMAIN, {DOMAIN: cfg})) + assert not setup_component(self.hass, DOMAIN, {DOMAIN: cfg}) def test_config_options(self): """Test configuration options.""" @@ -66,23 +65,23 @@ class TestCounter(unittest.TestCase): _LOGGER.debug('ENTITIES: %s', self.hass.states.entity_ids()) - self.assertEqual(count_start + 2, len(self.hass.states.entity_ids())) + assert count_start + 2 == len(self.hass.states.entity_ids()) self.hass.block_till_done() state_1 = self.hass.states.get('counter.test_1') state_2 = self.hass.states.get('counter.test_2') - self.assertIsNotNone(state_1) - self.assertIsNotNone(state_2) + assert state_1 is not None + assert state_2 is not None - self.assertEqual(0, int(state_1.state)) - self.assertNotIn(ATTR_ICON, state_1.attributes) - self.assertNotIn(ATTR_FRIENDLY_NAME, state_1.attributes) + assert 0 == int(state_1.state) + assert ATTR_ICON not in state_1.attributes + assert ATTR_FRIENDLY_NAME not in state_1.attributes - self.assertEqual(10, int(state_2.state)) - self.assertEqual('Hello World', - state_2.attributes.get(ATTR_FRIENDLY_NAME)) - self.assertEqual('mdi:work', state_2.attributes.get(ATTR_ICON)) + assert 10 == int(state_2.state) + assert 'Hello World' == \ + state_2.attributes.get(ATTR_FRIENDLY_NAME) + assert 'mdi:work' == state_2.attributes.get(ATTR_ICON) def test_methods(self): """Test increment, decrement, and reset methods.""" @@ -97,31 +96,31 @@ class TestCounter(unittest.TestCase): entity_id = 'counter.test_1' state = self.hass.states.get(entity_id) - self.assertEqual(0, int(state.state)) + assert 0 == int(state.state) increment(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(1, int(state.state)) + assert 1 == int(state.state) increment(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(2, int(state.state)) + assert 2 == int(state.state) decrement(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(1, int(state.state)) + assert 1 == int(state.state) reset(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(0, int(state.state)) + assert 0 == int(state.state) def test_methods_with_config(self): """Test increment, decrement, and reset methods with configuration.""" @@ -140,25 +139,25 @@ class TestCounter(unittest.TestCase): entity_id = 'counter.test' state = self.hass.states.get(entity_id) - self.assertEqual(10, int(state.state)) + assert 10 == int(state.state) increment(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(15, int(state.state)) + assert 15 == int(state.state) increment(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(20, int(state.state)) + assert 20 == int(state.state) decrement(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(15, int(state.state)) + assert 15 == int(state.state) @asyncio.coroutine diff --git a/tests/components/cover/test_mqtt.py b/tests/components/cover/test_mqtt.py index 282b1d287..09ac04f35 100644 --- a/tests/components/cover/test_mqtt.py +++ b/tests/components/cover/test_mqtt.py @@ -33,7 +33,7 @@ class TestCoverMQTT(unittest.TestCase): def test_state_via_state_topic(self): """Test the controlling state via topic.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -44,45 +44,45 @@ class TestCoverMQTT(unittest.TestCase): 'payload_close': 'CLOSE', 'payload_stop': 'STOP' } - })) + }) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNKNOWN, state.state) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_UNKNOWN == state.state + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'state-topic', '0') self.hass.block_till_done() state = self.hass.states.get('cover.test') - self.assertEqual(STATE_CLOSED, state.state) + assert STATE_CLOSED == state.state fire_mqtt_message(self.hass, 'state-topic', '50') self.hass.block_till_done() state = self.hass.states.get('cover.test') - self.assertEqual(STATE_OPEN, state.state) + assert STATE_OPEN == state.state fire_mqtt_message(self.hass, 'state-topic', '100') self.hass.block_till_done() state = self.hass.states.get('cover.test') - self.assertEqual(STATE_OPEN, state.state) + assert STATE_OPEN == state.state fire_mqtt_message(self.hass, 'state-topic', STATE_CLOSED) self.hass.block_till_done() state = self.hass.states.get('cover.test') - self.assertEqual(STATE_CLOSED, state.state) + assert STATE_CLOSED == state.state fire_mqtt_message(self.hass, 'state-topic', STATE_OPEN) self.hass.block_till_done() state = self.hass.states.get('cover.test') - self.assertEqual(STATE_OPEN, state.state) + assert STATE_OPEN == state.state def test_state_via_template(self): """Test the controlling state via topic.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -91,37 +91,37 @@ class TestCoverMQTT(unittest.TestCase): 'qos': 0, 'value_template': '{{ (value | multiply(0.01)) | int }}', } - })) + }) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN == state.state fire_mqtt_message(self.hass, 'state-topic', '10000') self.hass.block_till_done() state = self.hass.states.get('cover.test') - self.assertEqual(STATE_OPEN, state.state) + assert STATE_OPEN == state.state fire_mqtt_message(self.hass, 'state-topic', '99') self.hass.block_till_done() state = self.hass.states.get('cover.test') - self.assertEqual(STATE_CLOSED, state.state) + assert STATE_CLOSED == state.state def test_optimistic_state_change(self): """Test changing state optimistically.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', 'command_topic': 'command-topic', 'qos': 0, } - })) + }) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNKNOWN, state.state) - self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_UNKNOWN == state.state + assert state.attributes.get(ATTR_ASSUMED_STATE) self.hass.services.call( cover.DOMAIN, SERVICE_OPEN_COVER, @@ -132,7 +132,7 @@ class TestCoverMQTT(unittest.TestCase): 'command-topic', 'OPEN', 0, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get('cover.test') - self.assertEqual(STATE_OPEN, state.state) + assert STATE_OPEN == state.state self.hass.services.call( cover.DOMAIN, SERVICE_CLOSE_COVER, @@ -142,11 +142,11 @@ class TestCoverMQTT(unittest.TestCase): self.mock_publish.async_publish.assert_called_once_with( 'command-topic', 'CLOSE', 0, False) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_CLOSED, state.state) + assert STATE_CLOSED == state.state def test_send_open_cover_command(self): """Test the sending of open_cover.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -154,10 +154,10 @@ class TestCoverMQTT(unittest.TestCase): 'command_topic': 'command-topic', 'qos': 2 } - })) + }) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN == state.state self.hass.services.call( cover.DOMAIN, SERVICE_OPEN_COVER, @@ -167,11 +167,11 @@ class TestCoverMQTT(unittest.TestCase): self.mock_publish.async_publish.assert_called_once_with( 'command-topic', 'OPEN', 2, False) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN == state.state def test_send_close_cover_command(self): """Test the sending of close_cover.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -179,10 +179,10 @@ class TestCoverMQTT(unittest.TestCase): 'command_topic': 'command-topic', 'qos': 2 } - })) + }) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN == state.state self.hass.services.call( cover.DOMAIN, SERVICE_CLOSE_COVER, @@ -192,11 +192,11 @@ class TestCoverMQTT(unittest.TestCase): self.mock_publish.async_publish.assert_called_once_with( 'command-topic', 'CLOSE', 2, False) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN == state.state def test_send_stop__cover_command(self): """Test the sending of stop_cover.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -204,10 +204,10 @@ class TestCoverMQTT(unittest.TestCase): 'command_topic': 'command-topic', 'qos': 2 } - })) + }) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN == state.state self.hass.services.call( cover.DOMAIN, SERVICE_STOP_COVER, @@ -217,11 +217,11 @@ class TestCoverMQTT(unittest.TestCase): self.mock_publish.async_publish.assert_called_once_with( 'command-topic', 'STOP', 2, False) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN == state.state def test_current_cover_position(self): """Test the current cover position.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -231,42 +231,42 @@ class TestCoverMQTT(unittest.TestCase): 'payload_close': 'CLOSE', 'payload_stop': 'STOP' } - })) + }) state_attributes_dict = self.hass.states.get( 'cover.test').attributes - self.assertFalse('current_position' in state_attributes_dict) - self.assertFalse('current_tilt_position' in state_attributes_dict) - self.assertFalse(4 & self.hass.states.get( + assert not ('current_position' in state_attributes_dict) + assert not ('current_tilt_position' in state_attributes_dict) + assert not (4 & self.hass.states.get( 'cover.test').attributes['supported_features'] == 4) fire_mqtt_message(self.hass, 'state-topic', '0') self.hass.block_till_done() current_cover_position = self.hass.states.get( 'cover.test').attributes['current_position'] - self.assertEqual(0, current_cover_position) + assert 0 == current_cover_position fire_mqtt_message(self.hass, 'state-topic', '50') self.hass.block_till_done() current_cover_position = self.hass.states.get( 'cover.test').attributes['current_position'] - self.assertEqual(50, current_cover_position) + assert 50 == current_cover_position fire_mqtt_message(self.hass, 'state-topic', '101') self.hass.block_till_done() current_cover_position = self.hass.states.get( 'cover.test').attributes['current_position'] - self.assertEqual(50, current_cover_position) + assert 50 == current_cover_position fire_mqtt_message(self.hass, 'state-topic', 'non-numeric') self.hass.block_till_done() current_cover_position = self.hass.states.get( 'cover.test').attributes['current_position'] - self.assertEqual(50, current_cover_position) + assert 50 == current_cover_position def test_set_cover_position(self): """Test setting cover position.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -277,29 +277,29 @@ class TestCoverMQTT(unittest.TestCase): 'payload_close': 'CLOSE', 'payload_stop': 'STOP' } - })) + }) state_attributes_dict = self.hass.states.get( 'cover.test').attributes - self.assertFalse('current_position' in state_attributes_dict) - self.assertFalse('current_tilt_position' in state_attributes_dict) + assert not ('current_position' in state_attributes_dict) + assert not ('current_tilt_position' in state_attributes_dict) - self.assertTrue(4 & self.hass.states.get( - 'cover.test').attributes['supported_features'] == 4) + assert 4 & self.hass.states.get( + 'cover.test').attributes['supported_features'] == 4 fire_mqtt_message(self.hass, 'state-topic', '22') self.hass.block_till_done() state_attributes_dict = self.hass.states.get( 'cover.test').attributes - self.assertTrue('current_position' in state_attributes_dict) - self.assertFalse('current_tilt_position' in state_attributes_dict) + assert 'current_position' in state_attributes_dict + assert not ('current_tilt_position' in state_attributes_dict) current_cover_position = self.hass.states.get( 'cover.test').attributes['current_position'] - self.assertEqual(22, current_cover_position) + assert 22 == current_cover_position def test_set_position_templated(self): """Test setting cover position via template.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -311,7 +311,7 @@ class TestCoverMQTT(unittest.TestCase): 'payload_close': 'CLOSE', 'payload_stop': 'STOP' } - })) + }) self.hass.services.call( cover.DOMAIN, SERVICE_SET_COVER_POSITION, @@ -323,7 +323,7 @@ class TestCoverMQTT(unittest.TestCase): def test_set_position_untemplated(self): """Test setting cover position via template.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -334,7 +334,7 @@ class TestCoverMQTT(unittest.TestCase): 'payload_close': 'CLOSE', 'payload_stop': 'STOP' } - })) + }) self.hass.services.call( cover.DOMAIN, SERVICE_SET_COVER_POSITION, @@ -346,7 +346,7 @@ class TestCoverMQTT(unittest.TestCase): def test_no_command_topic(self): """Test with no command topic.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -357,14 +357,14 @@ class TestCoverMQTT(unittest.TestCase): 'tilt_command_topic': 'tilt-command', 'tilt_status_topic': 'tilt-status' } - })) + }) - self.assertEqual(240, self.hass.states.get( - 'cover.test').attributes['supported_features']) + assert 240 == self.hass.states.get( + 'cover.test').attributes['supported_features'] def test_with_command_topic_and_tilt(self): """Test with command topic and tilt config.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'command_topic': 'test', 'platform': 'mqtt', @@ -376,14 +376,14 @@ class TestCoverMQTT(unittest.TestCase): 'tilt_command_topic': 'tilt-command', 'tilt_status_topic': 'tilt-status' } - })) + }) - self.assertEqual(251, self.hass.states.get( - 'cover.test').attributes['supported_features']) + assert 251 == self.hass.states.get( + 'cover.test').attributes['supported_features'] def test_tilt_defaults(self): """Test the defaults.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -396,19 +396,19 @@ class TestCoverMQTT(unittest.TestCase): 'tilt_command_topic': 'tilt-command', 'tilt_status_topic': 'tilt-status' } - })) + }) state_attributes_dict = self.hass.states.get( 'cover.test').attributes - self.assertTrue('current_tilt_position' in state_attributes_dict) + assert 'current_tilt_position' in state_attributes_dict current_cover_position = self.hass.states.get( 'cover.test').attributes['current_tilt_position'] - self.assertEqual(STATE_UNKNOWN, current_cover_position) + assert STATE_UNKNOWN == current_cover_position def test_tilt_via_invocation_defaults(self): """Test tilt defaults on close/open.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -421,7 +421,7 @@ class TestCoverMQTT(unittest.TestCase): 'tilt_command_topic': 'tilt-command-topic', 'tilt_status_topic': 'tilt-status-topic' } - })) + }) self.hass.services.call( cover.DOMAIN, SERVICE_OPEN_COVER_TILT, @@ -442,7 +442,7 @@ class TestCoverMQTT(unittest.TestCase): def test_tilt_given_value(self): """Test tilting to a given value.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -457,7 +457,7 @@ class TestCoverMQTT(unittest.TestCase): 'tilt_opened_value': 400, 'tilt_closed_value': 125 } - })) + }) self.hass.services.call( cover.DOMAIN, SERVICE_OPEN_COVER_TILT, @@ -478,7 +478,7 @@ class TestCoverMQTT(unittest.TestCase): def test_tilt_via_topic(self): """Test tilt by updating status via MQTT.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -493,25 +493,25 @@ class TestCoverMQTT(unittest.TestCase): 'tilt_opened_value': 400, 'tilt_closed_value': 125 } - })) + }) fire_mqtt_message(self.hass, 'tilt-status-topic', '0') self.hass.block_till_done() current_cover_tilt_position = self.hass.states.get( 'cover.test').attributes['current_tilt_position'] - self.assertEqual(0, current_cover_tilt_position) + assert 0 == current_cover_tilt_position fire_mqtt_message(self.hass, 'tilt-status-topic', '50') self.hass.block_till_done() current_cover_tilt_position = self.hass.states.get( 'cover.test').attributes['current_tilt_position'] - self.assertEqual(50, current_cover_tilt_position) + assert 50 == current_cover_tilt_position def test_tilt_via_topic_altered_range(self): """Test tilt status via MQTT with altered tilt range.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -528,32 +528,32 @@ class TestCoverMQTT(unittest.TestCase): 'tilt_min': 0, 'tilt_max': 50 } - })) + }) fire_mqtt_message(self.hass, 'tilt-status-topic', '0') self.hass.block_till_done() current_cover_tilt_position = self.hass.states.get( 'cover.test').attributes['current_tilt_position'] - self.assertEqual(0, current_cover_tilt_position) + assert 0 == current_cover_tilt_position fire_mqtt_message(self.hass, 'tilt-status-topic', '50') self.hass.block_till_done() current_cover_tilt_position = self.hass.states.get( 'cover.test').attributes['current_tilt_position'] - self.assertEqual(100, current_cover_tilt_position) + assert 100 == current_cover_tilt_position fire_mqtt_message(self.hass, 'tilt-status-topic', '25') self.hass.block_till_done() current_cover_tilt_position = self.hass.states.get( 'cover.test').attributes['current_tilt_position'] - self.assertEqual(50, current_cover_tilt_position) + assert 50 == current_cover_tilt_position def test_tilt_position(self): """Test tilt via method invocation.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -568,7 +568,7 @@ class TestCoverMQTT(unittest.TestCase): 'tilt_opened_value': 400, 'tilt_closed_value': 125 } - })) + }) self.hass.services.call( cover.DOMAIN, SERVICE_SET_COVER_TILT_POSITION, @@ -581,7 +581,7 @@ class TestCoverMQTT(unittest.TestCase): def test_tilt_position_altered_range(self): """Test tilt via method invocation with altered range.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -598,7 +598,7 @@ class TestCoverMQTT(unittest.TestCase): 'tilt_min': 0, 'tilt_max': 50 } - })) + }) self.hass.services.call( cover.DOMAIN, SERVICE_SET_COVER_TILT_POSITION, @@ -618,7 +618,7 @@ class TestCoverMQTT(unittest.TestCase): False, None, 100, 0, 0, 100, False, False, None, None, None, None, None) - self.assertEqual(44, mqtt_cover.find_percentage_in_range(44)) + assert 44 == mqtt_cover.find_percentage_in_range(44) def test_find_percentage_in_range_altered(self): """Test find percentage in range with altered range.""" @@ -629,7 +629,7 @@ class TestCoverMQTT(unittest.TestCase): False, None, 180, 80, 80, 180, False, False, None, None, None, None, None) - self.assertEqual(40, mqtt_cover.find_percentage_in_range(120)) + assert 40 == mqtt_cover.find_percentage_in_range(120) def test_find_percentage_in_range_defaults_inverted(self): """Test find percentage in range with default range but inverted.""" @@ -640,7 +640,7 @@ class TestCoverMQTT(unittest.TestCase): False, None, 100, 0, 0, 100, False, True, None, None, None, None, None) - self.assertEqual(56, mqtt_cover.find_percentage_in_range(44)) + assert 56 == mqtt_cover.find_percentage_in_range(44) def test_find_percentage_in_range_altered_inverted(self): """Test find percentage in range with altered range and inverted.""" @@ -651,7 +651,7 @@ class TestCoverMQTT(unittest.TestCase): False, None, 180, 80, 80, 180, False, True, None, None, None, None, None) - self.assertEqual(60, mqtt_cover.find_percentage_in_range(120)) + assert 60 == mqtt_cover.find_percentage_in_range(120) def test_find_in_range_defaults(self): """Test find in range with default range.""" @@ -662,7 +662,7 @@ class TestCoverMQTT(unittest.TestCase): False, None, 100, 0, 0, 100, False, False, None, None, None, None, None) - self.assertEqual(44, mqtt_cover.find_in_range_from_percent(44)) + assert 44 == mqtt_cover.find_in_range_from_percent(44) def test_find_in_range_altered(self): """Test find in range with altered range.""" @@ -673,7 +673,7 @@ class TestCoverMQTT(unittest.TestCase): False, None, 180, 80, 80, 180, False, False, None, None, None, None, None) - self.assertEqual(120, mqtt_cover.find_in_range_from_percent(40)) + assert 120 == mqtt_cover.find_in_range_from_percent(40) def test_find_in_range_defaults_inverted(self): """Test find in range with default range but inverted.""" @@ -684,7 +684,7 @@ class TestCoverMQTT(unittest.TestCase): False, None, 100, 0, 0, 100, False, True, None, None, None, None, None) - self.assertEqual(44, mqtt_cover.find_in_range_from_percent(56)) + assert 44 == mqtt_cover.find_in_range_from_percent(56) def test_find_in_range_altered_inverted(self): """Test find in range with altered range and inverted.""" @@ -695,25 +695,25 @@ class TestCoverMQTT(unittest.TestCase): False, None, 180, 80, 80, 180, False, True, None, None, None, None, None) - self.assertEqual(120, mqtt_cover.find_in_range_from_percent(60)) + assert 120 == mqtt_cover.find_in_range_from_percent(60) def test_availability_without_topic(self): """Test availability without defined availability topic.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic' } - })) + }) state = self.hass.states.get('cover.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state def test_availability_by_defaults(self): """Test availability by defaults with defined topic.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -721,26 +721,26 @@ class TestCoverMQTT(unittest.TestCase): 'command_topic': 'command-topic', 'availability_topic': 'availability-topic' } - })) + }) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'online') self.hass.block_till_done() state = self.hass.states.get('cover.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'offline') self.hass.block_till_done() state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def test_availability_by_custom_payload(self): """Test availability by custom payload with defined topic.""" - self.assertTrue(setup_component(self.hass, cover.DOMAIN, { + assert setup_component(self.hass, cover.DOMAIN, { cover.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -750,22 +750,22 @@ class TestCoverMQTT(unittest.TestCase): 'payload_available': 'good', 'payload_not_available': 'nogood' } - })) + }) state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'good') self.hass.block_till_done() state = self.hass.states.get('cover.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'nogood') self.hass.block_till_done() state = self.hass.states.get('cover.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state async def test_discovery_removal_cover(hass, mqtt_mock, caplog): diff --git a/tests/components/cover/test_rfxtrx.py b/tests/components/cover/test_rfxtrx.py index ab8b8f9a9..474e36050 100644 --- a/tests/components/cover/test_rfxtrx.py +++ b/tests/components/cover/test_rfxtrx.py @@ -28,18 +28,18 @@ class TestCoverRfxtrx(unittest.TestCase): def test_valid_config(self): """Test configuration.""" - self.assertTrue(setup_component(self.hass, 'cover', { + assert setup_component(self.hass, 'cover', { 'cover': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'0b1100cd0213c7f210010f51': { 'name': 'Test', rfxtrx_core.ATTR_FIREEVENT: True} - }}})) + }}}) def test_invalid_config_capital_letters(self): """Test configuration.""" - self.assertFalse(setup_component(self.hass, 'cover', { + assert not setup_component(self.hass, 'cover', { 'cover': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': @@ -47,11 +47,11 @@ class TestCoverRfxtrx(unittest.TestCase): 'name': 'Test', 'packetid': '0b1100cd0213c7f210010f51', 'signal_repetitions': 3} - }}})) + }}}) def test_invalid_config_extra_key(self): """Test configuration.""" - self.assertFalse(setup_component(self.hass, 'cover', { + assert not setup_component(self.hass, 'cover', { 'cover': {'platform': 'rfxtrx', 'automatic_add': True, 'invalid_key': 'afda', @@ -60,11 +60,11 @@ class TestCoverRfxtrx(unittest.TestCase): 'name': 'Test', 'packetid': '0b1100cd0213c7f210010f51', rfxtrx_core.ATTR_FIREEVENT: True} - }}})) + }}}) def test_invalid_config_capital_packetid(self): """Test configuration.""" - self.assertFalse(setup_component(self.hass, 'cover', { + assert not setup_component(self.hass, 'cover', { 'cover': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': @@ -72,52 +72,52 @@ class TestCoverRfxtrx(unittest.TestCase): 'name': 'Test', 'packetid': 'AA1100cd0213c7f210010f51', rfxtrx_core.ATTR_FIREEVENT: True} - }}})) + }}}) def test_invalid_config_missing_packetid(self): """Test configuration.""" - self.assertFalse(setup_component(self.hass, 'cover', { + assert not setup_component(self.hass, 'cover', { 'cover': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'213c7f216': { 'name': 'Test', rfxtrx_core.ATTR_FIREEVENT: True} - }}})) + }}}) def test_default_config(self): """Test with 0 cover.""" - self.assertTrue(setup_component(self.hass, 'cover', { + assert setup_component(self.hass, 'cover', { 'cover': {'platform': 'rfxtrx', - 'devices': {}}})) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + 'devices': {}}}) + assert 0 == len(rfxtrx_core.RFX_DEVICES) def test_one_cover(self): """Test with 1 cover.""" - self.assertTrue(setup_component(self.hass, 'cover', { + assert setup_component(self.hass, 'cover', { 'cover': {'platform': 'rfxtrx', 'devices': {'0b1400cd0213c7f210010f51': { 'name': 'Test' - }}}})) + }}}}) import RFXtrx as rfxtrxmod rfxtrx_core.RFXOBJECT =\ rfxtrxmod.Core("", transport_protocol=rfxtrxmod.DummyTransport) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) for id in rfxtrx_core.RFX_DEVICES: entity = rfxtrx_core.RFX_DEVICES[id] - self.assertEqual(entity.signal_repetitions, 1) - self.assertFalse(entity.should_fire_event) - self.assertFalse(entity.should_poll) + assert entity.signal_repetitions == 1 + assert not entity.should_fire_event + assert not entity.should_poll entity.open_cover() entity.close_cover() entity.stop_cover() def test_several_covers(self): """Test with 3 covers.""" - self.assertTrue(setup_component(self.hass, 'cover', { + assert setup_component(self.hass, 'cover', { 'cover': {'platform': 'rfxtrx', 'signal_repetitions': 3, 'devices': @@ -127,13 +127,13 @@ class TestCoverRfxtrx(unittest.TestCase): 'name': 'Bath'}, '0b1100101118cdea02010f70': { 'name': 'Living'} - }}})) + }}}) - self.assertEqual(3, len(rfxtrx_core.RFX_DEVICES)) + assert 3 == len(rfxtrx_core.RFX_DEVICES) device_num = 0 for id in rfxtrx_core.RFX_DEVICES: entity = rfxtrx_core.RFX_DEVICES[id] - self.assertEqual(entity.signal_repetitions, 3) + assert entity.signal_repetitions == 3 if entity.name == 'Living': device_num = device_num + 1 elif entity.name == 'Bath': @@ -141,14 +141,14 @@ class TestCoverRfxtrx(unittest.TestCase): elif entity.name == 'Test': device_num = device_num + 1 - self.assertEqual(3, device_num) + assert 3 == device_num def test_discover_covers(self): """Test with discovery of covers.""" - self.assertTrue(setup_component(self.hass, 'cover', { + assert setup_component(self.hass, 'cover', { 'cover': {'platform': 'rfxtrx', 'automatic_add': True, - 'devices': {}}})) + 'devices': {}}}) event = rfxtrx_core.get_rfx_object('0a140002f38cae010f0070') event.data = bytearray([0x0A, 0x14, 0x00, 0x02, 0xF3, 0x8C, @@ -156,7 +156,7 @@ class TestCoverRfxtrx(unittest.TestCase): for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) event = rfxtrx_core.get_rfx_object('0a1400adf394ab020e0060') event.data = bytearray([0x0A, 0x14, 0x00, 0xAD, 0xF3, 0x94, @@ -164,14 +164,14 @@ class TestCoverRfxtrx(unittest.TestCase): for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a sensor event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray(b'\nR\x08^\x07\x01\x00\xb3\x1b\x02y') for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a light event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') @@ -179,14 +179,14 @@ class TestCoverRfxtrx(unittest.TestCase): 0xcd, 0xea, 0x01, 0x02, 0x0f, 0x70]) for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) def test_discover_cover_noautoadd(self): """Test with discovery of cover when auto add is False.""" - self.assertTrue(setup_component(self.hass, 'cover', { + assert setup_component(self.hass, 'cover', { 'cover': {'platform': 'rfxtrx', 'automatic_add': False, - 'devices': {}}})) + 'devices': {}}}) event = rfxtrx_core.get_rfx_object('0a1400adf394ab010d0060') event.data = bytearray([0x0A, 0x14, 0x00, 0xAD, 0xF3, 0x94, @@ -194,21 +194,21 @@ class TestCoverRfxtrx(unittest.TestCase): for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) event = rfxtrx_core.get_rfx_object('0a1400adf394ab020e0060') event.data = bytearray([0x0A, 0x14, 0x00, 0xAD, 0xF3, 0x94, 0xAB, 0x02, 0x0E, 0x00, 0x60]) for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a sensor event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray(b'\nR\x08^\x07\x01\x00\xb3\x1b\x02y') for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a light event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') @@ -216,4 +216,4 @@ class TestCoverRfxtrx(unittest.TestCase): 0x18, 0xcd, 0xea, 0x01, 0x02, 0x0f, 0x70]) for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) diff --git a/tests/components/device_tracker/test_asuswrt.py b/tests/components/device_tracker/test_asuswrt.py index d43a7d539..09f14dc97 100644 --- a/tests/components/device_tracker/test_asuswrt.py +++ b/tests/components/device_tracker/test_asuswrt.py @@ -103,5 +103,5 @@ class TestComponentsDeviceTrackerASUSWRT(unittest.TestCase): conf_dict[DOMAIN][CONF_MODE] = 'router' conf_dict[DOMAIN][CONF_PROTOCOL] = 'ssh' conf_dict[DOMAIN][CONF_PORT] = 22 - self.assertEqual(asuswrt_mock.call_count, 1) - self.assertEqual(asuswrt_mock.call_args, mock.call(conf_dict[DOMAIN])) + assert asuswrt_mock.call_count == 1 + assert asuswrt_mock.call_args == mock.call(conf_dict[DOMAIN]) diff --git a/tests/components/device_tracker/test_ddwrt.py b/tests/components/device_tracker/test_ddwrt.py index 3e60e1bae..457ef6b47 100644 --- a/tests/components/device_tracker/test_ddwrt.py +++ b/tests/components/device_tracker/test_ddwrt.py @@ -69,9 +69,8 @@ class TestDdwrt(unittest.TestCase): CONF_PASSWORD: '0' }}) - self.assertTrue( - 'Failed to authenticate' in - str(mock_error.call_args_list[-1])) + assert 'Failed to authenticate' in \ + str(mock_error.call_args_list[-1]) @mock.patch('homeassistant.components.device_tracker.ddwrt._LOGGER.error') def test_invalid_response(self, mock_error): @@ -89,9 +88,8 @@ class TestDdwrt(unittest.TestCase): CONF_PASSWORD: '0' }}) - self.assertTrue( - 'Invalid response from DD-WRT' in - str(mock_error.call_args_list[-1])) + assert 'Invalid response from DD-WRT' in \ + str(mock_error.call_args_list[-1]) @mock.patch('homeassistant.components.device_tracker._LOGGER.error') @mock.patch('homeassistant.components.device_tracker.' @@ -106,9 +104,8 @@ class TestDdwrt(unittest.TestCase): CONF_USERNAME: 'fake_user', CONF_PASSWORD: '0' }}) - self.assertTrue( - 'Error setting up platform' in - str(error_mock.call_args_list[-1])) + assert 'Error setting up platform' in \ + str(error_mock.call_args_list[-1]) @mock.patch('homeassistant.components.device_tracker.ddwrt.requests.get', side_effect=requests.exceptions.Timeout) @@ -124,9 +121,8 @@ class TestDdwrt(unittest.TestCase): CONF_PASSWORD: '0' }}) - self.assertTrue( - 'Connection to the router timed out' in - str(mock_error.call_args_list[-1])) + assert 'Connection to the router timed out' in \ + str(mock_error.call_args_list[-1]) def test_scan_devices(self): """Test creating device info (MAC, name) from response. @@ -158,8 +154,8 @@ class TestDdwrt(unittest.TestCase): path = self.hass.config.path(device_tracker.YAML_DEVICES) devices = config.load_yaml_config_file(path) for device in devices: - self.assertIn(devices[device]['mac'], status_lan) - self.assertIn(slugify(devices[device]['name']), status_lan) + assert devices[device]['mac'] in status_lan + assert slugify(devices[device]['name']) in status_lan def test_device_name_no_data(self): """Test creating device info (MAC only) when no response.""" @@ -185,7 +181,7 @@ class TestDdwrt(unittest.TestCase): status_lan = load_fixture('Ddwrt_Status_Lan.txt') for device in devices: _LOGGER.error(devices[device]) - self.assertIn(devices[device]['mac'], status_lan) + assert devices[device]['mac'] in status_lan def test_device_name_no_dhcp(self): """Test creating device info (MAC) when missing dhcp response.""" @@ -213,7 +209,7 @@ class TestDdwrt(unittest.TestCase): status_lan = load_fixture('Ddwrt_Status_Lan.txt') for device in devices: _LOGGER.error(devices[device]) - self.assertIn(devices[device]['mac'], status_lan) + assert devices[device]['mac'] in status_lan def test_update_no_data(self): """Test error handling of no response when active devices checked.""" diff --git a/tests/components/device_tracker/test_init.py b/tests/components/device_tracker/test_init.py index b1b68ff92..6ceb4674f 100644 --- a/tests/components/device_tracker/test_init.py +++ b/tests/components/device_tracker/test_init.py @@ -25,6 +25,7 @@ from homeassistant.helpers.json import JSONEncoder from tests.common import ( get_test_home_assistant, fire_time_changed, patch_yaml_files, assert_setup_component, mock_restore_cache) +import pytest TEST_PLATFORM = {device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}} @@ -57,11 +58,11 @@ class TestComponentsDeviceTracker(unittest.TestCase): self.hass.states.set(entity_id, STATE_HOME) - self.assertTrue(device_tracker.is_on(self.hass, entity_id)) + assert device_tracker.is_on(self.hass, entity_id) self.hass.states.set(entity_id, STATE_NOT_HOME) - self.assertFalse(device_tracker.is_on(self.hass, entity_id)) + assert not device_tracker.is_on(self.hass, entity_id) # pylint: disable=no-self-use def test_reading_broken_yaml_config(self): @@ -103,13 +104,13 @@ class TestComponentsDeviceTracker(unittest.TestCase): TEST_PLATFORM) config = device_tracker.load_config(self.yaml_devices, self.hass, device.consider_home)[0] - self.assertEqual(device.dev_id, config.dev_id) - self.assertEqual(device.track, config.track) - self.assertEqual(device.mac, config.mac) - self.assertEqual(device.config_picture, config.config_picture) - self.assertEqual(device.away_hide, config.away_hide) - self.assertEqual(device.consider_home, config.consider_home) - self.assertEqual(device.icon, config.icon) + assert device.dev_id == config.dev_id + assert device.track == config.track + assert device.mac == config.mac + assert device.config_picture == config.config_picture + assert device.away_hide == config.away_hide + assert device.consider_home == config.consider_home + assert device.icon == config.icon # pylint: disable=invalid-name @patch('homeassistant.components.device_tracker._LOGGER.warning') @@ -157,7 +158,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): 'AB:CD:EF:GH:IJ', 'Test name', gravatar='test@example.com') gravatar_url = ("https://www.gravatar.com/avatar/" "55502f40dc8b7c769880b10874abc9d0.jpg?s=80&d=wavatar") - self.assertEqual(device.config_picture, gravatar_url) + assert device.config_picture == gravatar_url def test_gravatar_and_picture(self): """Test that Gravatar overrides picture.""" @@ -168,7 +169,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): gravatar='test@example.com') gravatar_url = ("https://www.gravatar.com/avatar/" "55502f40dc8b7c769880b10874abc9d0.jpg?s=80&d=wavatar") - self.assertEqual(device.config_picture, gravatar_url) + assert device.config_picture == gravatar_url @patch( 'homeassistant.components.device_tracker.DeviceTracker.see') @@ -206,8 +207,8 @@ class TestComponentsDeviceTracker(unittest.TestCase): }}) self.hass.block_till_done() - self.assertEqual(STATE_HOME, - self.hass.states.get('device_tracker.dev1').state) + assert STATE_HOME == \ + self.hass.states.get('device_tracker.dev1').state scanner.leave_home('DEV1') @@ -216,8 +217,8 @@ class TestComponentsDeviceTracker(unittest.TestCase): fire_time_changed(self.hass, scan_time) self.hass.block_till_done() - self.assertEqual(STATE_NOT_HOME, - self.hass.states.get('device_tracker.dev1').state) + assert STATE_NOT_HOME == \ + self.hass.states.get('device_tracker.dev1').state def test_entity_attributes(self): """Test the entity attributes.""" @@ -238,9 +239,9 @@ class TestComponentsDeviceTracker(unittest.TestCase): attrs = self.hass.states.get(entity_id).attributes - self.assertEqual(friendly_name, attrs.get(ATTR_FRIENDLY_NAME)) - self.assertEqual(icon, attrs.get(ATTR_ICON)) - self.assertEqual(picture, attrs.get(ATTR_ENTITY_PICTURE)) + assert friendly_name == attrs.get(ATTR_FRIENDLY_NAME) + assert icon == attrs.get(ATTR_ICON) + assert picture == attrs.get(ATTR_ENTITY_PICTURE) def test_device_hidden(self): """Test hidden devices.""" @@ -258,8 +259,8 @@ class TestComponentsDeviceTracker(unittest.TestCase): assert setup_component(self.hass, device_tracker.DOMAIN, TEST_PLATFORM) - self.assertTrue(self.hass.states.get(entity_id) - .attributes.get(ATTR_HIDDEN)) + assert self.hass.states.get(entity_id) \ + .attributes.get(ATTR_HIDDEN) def test_group_all_devices(self): """Test grouping of devices.""" @@ -279,10 +280,9 @@ class TestComponentsDeviceTracker(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(device_tracker.ENTITY_ID_ALL_DEVICES) - self.assertIsNotNone(state) - self.assertEqual(STATE_NOT_HOME, state.state) - self.assertSequenceEqual((entity_id,), - state.attributes.get(ATTR_ENTITY_ID)) + assert state is not None + assert STATE_NOT_HOME == state.state + assert (entity_id,) == state.attributes.get(ATTR_ENTITY_ID) @patch('homeassistant.components.device_tracker.DeviceTracker.async_see') def test_see_service(self, mock_see): @@ -302,8 +302,8 @@ class TestComponentsDeviceTracker(unittest.TestCase): device_tracker.see(self.hass, **params) self.hass.block_till_done() assert mock_see.call_count == 1 - self.assertEqual(mock_see.call_count, 1) - self.assertEqual(mock_see.call_args, call(**params)) + assert mock_see.call_count == 1 + assert mock_see.call_args == call(**params) mock_see.reset_mock() params['dev_id'] += chr(233) # e' acute accent from icloud @@ -311,8 +311,8 @@ class TestComponentsDeviceTracker(unittest.TestCase): device_tracker.see(self.hass, **params) self.hass.block_till_done() assert mock_see.call_count == 1 - self.assertEqual(mock_see.call_count, 1) - self.assertEqual(mock_see.call_args, call(**params)) + assert mock_see.call_count == 1 + assert mock_see.call_args == call(**params) def test_new_device_event_fired(self): """Test that the device tracker will fire an event.""" @@ -375,8 +375,8 @@ class TestComponentsDeviceTracker(unittest.TestCase): def test_see_state(self): """Test device tracker see records state correctly.""" - self.assertTrue(setup_component(self.hass, device_tracker.DOMAIN, - TEST_PLATFORM)) + assert setup_component(self.hass, device_tracker.DOMAIN, + TEST_PLATFORM) params = { 'mac': 'AA:BB:CC:DD:EE:FF', @@ -401,17 +401,17 @@ class TestComponentsDeviceTracker(unittest.TestCase): state = self.hass.states.get('device_tracker.examplecom') attrs = state.attributes - self.assertEqual(state.state, 'Work') - self.assertEqual(state.object_id, 'examplecom') - self.assertEqual(state.name, 'example.com') - self.assertEqual(attrs['friendly_name'], 'example.com') - self.assertEqual(attrs['battery'], 100) - self.assertEqual(attrs['latitude'], 0.3) - self.assertEqual(attrs['longitude'], 0.8) - self.assertEqual(attrs['test'], 'test') - self.assertEqual(attrs['gps_accuracy'], 1) - self.assertEqual(attrs['source_type'], 'gps') - self.assertEqual(attrs['number'], 1) + assert state.state == 'Work' + assert state.object_id == 'examplecom' + assert state.name == 'example.com' + assert attrs['friendly_name'] == 'example.com' + assert attrs['battery'] == 100 + assert attrs['latitude'] == 0.3 + assert attrs['longitude'] == 0.8 + assert attrs['test'] == 'test' + assert attrs['gps_accuracy'] == 1 + assert attrs['source_type'] == 'gps' + assert attrs['number'] == 1 def test_see_passive_zone_state(self): """Test that the device tracker sets gps for passive trackers.""" @@ -447,15 +447,15 @@ class TestComponentsDeviceTracker(unittest.TestCase): state = self.hass.states.get('device_tracker.dev1') attrs = state.attributes - self.assertEqual(STATE_HOME, state.state) - self.assertEqual(state.object_id, 'dev1') - self.assertEqual(state.name, 'dev1') - self.assertEqual(attrs.get('friendly_name'), 'dev1') - self.assertEqual(attrs.get('latitude'), 1) - self.assertEqual(attrs.get('longitude'), 2) - self.assertEqual(attrs.get('gps_accuracy'), 0) - self.assertEqual(attrs.get('source_type'), - device_tracker.SOURCE_TYPE_ROUTER) + assert STATE_HOME == state.state + assert state.object_id == 'dev1' + assert state.name == 'dev1' + assert attrs.get('friendly_name') == 'dev1' + assert attrs.get('latitude') == 1 + assert attrs.get('longitude') == 2 + assert attrs.get('gps_accuracy') == 0 + assert attrs.get('source_type') == \ + device_tracker.SOURCE_TYPE_ROUTER scanner.leave_home('dev1') @@ -466,15 +466,15 @@ class TestComponentsDeviceTracker(unittest.TestCase): state = self.hass.states.get('device_tracker.dev1') attrs = state.attributes - self.assertEqual(STATE_NOT_HOME, state.state) - self.assertEqual(state.object_id, 'dev1') - self.assertEqual(state.name, 'dev1') - self.assertEqual(attrs.get('friendly_name'), 'dev1') - self.assertEqual(attrs.get('latitude'), None) - self.assertEqual(attrs.get('longitude'), None) - self.assertEqual(attrs.get('gps_accuracy'), None) - self.assertEqual(attrs.get('source_type'), - device_tracker.SOURCE_TYPE_ROUTER) + assert STATE_NOT_HOME == state.state + assert state.object_id == 'dev1' + assert state.name == 'dev1' + assert attrs.get('friendly_name') == 'dev1' + assert attrs.get('latitude')is None + assert attrs.get('longitude')is None + assert attrs.get('gps_accuracy')is None + assert attrs.get('source_type') == \ + device_tracker.SOURCE_TYPE_ROUTER @patch('homeassistant.components.device_tracker._LOGGER.warning') def test_see_failures(self, mock_warning): @@ -486,7 +486,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): tracker.see(mac=567, host_name="Number MAC") # No device id or MAC(not added) - with self.assertRaises(HomeAssistantError): + with pytest.raises(HomeAssistantError): run_coroutine_threadsafe( tracker.async_see(), self.hass.loop).result() assert mock_warning.call_count == 0 diff --git a/tests/components/device_tracker/test_mqtt.py b/tests/components/device_tracker/test_mqtt.py index 8e4d0dc27..e760db151 100644 --- a/tests/components/device_tracker/test_mqtt.py +++ b/tests/components/device_tracker/test_mqtt.py @@ -36,7 +36,7 @@ class TestComponentsDeviceTrackerMQTT(unittest.TestCase): @asyncio.coroutine def mock_setup_scanner(hass, config, see, discovery_info=None): """Check that Qos was added by validation.""" - self.assertTrue('qos' in config) + assert 'qos' in config with patch('homeassistant.components.device_tracker.mqtt.' 'async_setup_scanner', autospec=True, @@ -68,7 +68,7 @@ class TestComponentsDeviceTrackerMQTT(unittest.TestCase): }) fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() - self.assertEqual(location, self.hass.states.get(entity_id).state) + assert location == self.hass.states.get(entity_id).state def test_single_level_wildcard_topic(self): """Test single level wildcard topic.""" @@ -87,7 +87,7 @@ class TestComponentsDeviceTrackerMQTT(unittest.TestCase): }) fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() - self.assertEqual(location, self.hass.states.get(entity_id).state) + assert location == self.hass.states.get(entity_id).state def test_multi_level_wildcard_topic(self): """Test multi level wildcard topic.""" @@ -106,7 +106,7 @@ class TestComponentsDeviceTrackerMQTT(unittest.TestCase): }) fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() - self.assertEqual(location, self.hass.states.get(entity_id).state) + assert location == self.hass.states.get(entity_id).state def test_single_level_wildcard_topic_not_matching(self): """Test not matching single level wildcard topic.""" @@ -125,7 +125,7 @@ class TestComponentsDeviceTrackerMQTT(unittest.TestCase): }) fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() - self.assertIsNone(self.hass.states.get(entity_id)) + assert self.hass.states.get(entity_id) is None def test_multi_level_wildcard_topic_not_matching(self): """Test not matching multi level wildcard topic.""" @@ -144,4 +144,4 @@ class TestComponentsDeviceTrackerMQTT(unittest.TestCase): }) fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() - self.assertIsNone(self.hass.states.get(entity_id)) + assert self.hass.states.get(entity_id) is None diff --git a/tests/components/device_tracker/test_mqtt_json.py b/tests/components/device_tracker/test_mqtt_json.py index 41c1d9c08..44d687a4d 100644 --- a/tests/components/device_tracker/test_mqtt_json.py +++ b/tests/components/device_tracker/test_mqtt_json.py @@ -46,7 +46,7 @@ class TestComponentsDeviceTrackerJSONMQTT(unittest.TestCase): @asyncio.coroutine def mock_setup_scanner(hass, config, see, discovery_info=None): """Check that Qos was added by validation.""" - self.assertTrue('qos' in config) + assert 'qos' in config with patch('homeassistant.components.device_tracker.mqtt_json.' 'async_setup_scanner', autospec=True, @@ -77,8 +77,8 @@ class TestComponentsDeviceTrackerJSONMQTT(unittest.TestCase): fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() state = self.hass.states.get('device_tracker.zanzito') - self.assertEqual(state.attributes.get('latitude'), 2.0) - self.assertEqual(state.attributes.get('longitude'), 1.0) + assert state.attributes.get('latitude') == 2.0 + assert state.attributes.get('longitude') == 1.0 def test_non_json_message(self): """Test receiving a non JSON message.""" @@ -96,10 +96,9 @@ class TestComponentsDeviceTrackerJSONMQTT(unittest.TestCase): with self.assertLogs(level='ERROR') as test_handle: fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() - self.assertIn( - "ERROR:homeassistant.components.device_tracker.mqtt_json:" - "Error parsing JSON payload: home", - test_handle.output[0]) + assert "ERROR:homeassistant.components.device_tracker.mqtt_json:" \ + "Error parsing JSON payload: home" in \ + test_handle.output[0] def test_incomplete_message(self): """Test receiving an incomplete message.""" @@ -117,11 +116,10 @@ class TestComponentsDeviceTrackerJSONMQTT(unittest.TestCase): with self.assertLogs(level='ERROR') as test_handle: fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() - self.assertIn( - "ERROR:homeassistant.components.device_tracker.mqtt_json:" - "Skipping update for following data because of missing " - "or malformatted data: {\"longitude\": 2.0}", - test_handle.output[0]) + assert "ERROR:homeassistant.components.device_tracker.mqtt_json:" \ + "Skipping update for following data because of missing " \ + "or malformatted data: {\"longitude\": 2.0}" in \ + test_handle.output[0] def test_single_level_wildcard_topic(self): """Test single level wildcard topic.""" @@ -139,8 +137,8 @@ class TestComponentsDeviceTrackerJSONMQTT(unittest.TestCase): fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() state = self.hass.states.get('device_tracker.zanzito') - self.assertEqual(state.attributes.get('latitude'), 2.0) - self.assertEqual(state.attributes.get('longitude'), 1.0) + assert state.attributes.get('latitude') == 2.0 + assert state.attributes.get('longitude') == 1.0 def test_multi_level_wildcard_topic(self): """Test multi level wildcard topic.""" @@ -158,8 +156,8 @@ class TestComponentsDeviceTrackerJSONMQTT(unittest.TestCase): fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() state = self.hass.states.get('device_tracker.zanzito') - self.assertEqual(state.attributes.get('latitude'), 2.0) - self.assertEqual(state.attributes.get('longitude'), 1.0) + assert state.attributes.get('latitude') == 2.0 + assert state.attributes.get('longitude') == 1.0 def test_single_level_wildcard_topic_not_matching(self): """Test not matching single level wildcard topic.""" @@ -177,7 +175,7 @@ class TestComponentsDeviceTrackerJSONMQTT(unittest.TestCase): }) fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() - self.assertIsNone(self.hass.states.get(entity_id)) + assert self.hass.states.get(entity_id) is None def test_multi_level_wildcard_topic_not_matching(self): """Test not matching multi level wildcard topic.""" @@ -195,4 +193,4 @@ class TestComponentsDeviceTrackerJSONMQTT(unittest.TestCase): }) fire_mqtt_message(self.hass, topic, location) self.hass.block_till_done() - self.assertIsNone(self.hass.states.get(entity_id)) + assert self.hass.states.get(entity_id) is None diff --git a/tests/components/device_tracker/test_owntracks.py b/tests/components/device_tracker/test_owntracks.py index 8883ea226..dcd66ed2a 100644 --- a/tests/components/device_tracker/test_owntracks.py +++ b/tests/components/device_tracker/test_owntracks.py @@ -299,27 +299,27 @@ class BaseMQTT(unittest.TestCase): def assert_location_state(self, location): """Test the assertion of a location state.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) - self.assertEqual(state.state, location) + assert state.state == location def assert_location_latitude(self, latitude): """Test the assertion of a location latitude.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) - self.assertEqual(state.attributes.get('latitude'), latitude) + assert state.attributes.get('latitude') == latitude def assert_location_longitude(self, longitude): """Test the assertion of a location longitude.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) - self.assertEqual(state.attributes.get('longitude'), longitude) + assert state.attributes.get('longitude') == longitude def assert_location_accuracy(self, accuracy): """Test the assertion of a location accuracy.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) - self.assertEqual(state.attributes.get('gps_accuracy'), accuracy) + assert state.attributes.get('gps_accuracy') == accuracy def assert_location_source_type(self, source_type): """Test the assertion of source_type.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) - self.assertEqual(state.attributes.get('source_type'), source_type) + assert state.attributes.get('source_type') == source_type class TestDeviceTrackerOwnTracks(BaseMQTT): @@ -382,19 +382,19 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): """Test the assertion of a mobile beacon tracker state.""" dev_id = MOBILE_BEACON_FMT.format(beacon) state = self.hass.states.get(dev_id) - self.assertEqual(state.state, location) + assert state.state == location def assert_mobile_tracker_latitude(self, latitude, beacon=IBEACON_DEVICE): """Test the assertion of a mobile beacon tracker latitude.""" dev_id = MOBILE_BEACON_FMT.format(beacon) state = self.hass.states.get(dev_id) - self.assertEqual(state.attributes.get('latitude'), latitude) + assert state.attributes.get('latitude') == latitude def assert_mobile_tracker_accuracy(self, accuracy, beacon=IBEACON_DEVICE): """Test the assertion of a mobile beacon tracker accuracy.""" dev_id = MOBILE_BEACON_FMT.format(beacon) state = self.hass.states.get(dev_id) - self.assertEqual(state.attributes.get('gps_accuracy'), accuracy) + assert state.attributes.get('gps_accuracy') == accuracy def test_location_invalid_devid(self): # pylint: disable=invalid-name """Test the update of a location.""" @@ -460,7 +460,7 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.assert_location_state('outer') # Left clean zone state - self.assertFalse(self.context.regions_entered[USER]) + assert not self.context.regions_entered[USER] self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE) @@ -480,7 +480,7 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.send_message(EVENT_TOPIC, message) # Left clean zone state - self.assertFalse(self.context.regions_entered[USER]) + assert not self.context.regions_entered[USER] def test_event_gps_entry_inaccurate(self): """Test the event for inaccurate entry.""" @@ -511,7 +511,7 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.assert_location_state('inner') # But does exit region correctly - self.assertFalse(self.context.regions_entered[USER]) + assert not self.context.regions_entered[USER] def test_event_gps_entry_exit_zero_accuracy(self): """Test entry/exit events with accuracy zero.""" @@ -530,7 +530,7 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.assert_location_state('inner') # But does exit region correctly - self.assertFalse(self.context.regions_entered[USER]) + assert not self.context.regions_entered[USER] def test_event_gps_exit_outside_zone_sets_away(self): """Test the event for exit zone.""" @@ -730,7 +730,7 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.assert_location_state('inner') # Left clean zone state - self.assertFalse(self.context.regions_entered[USER]) + assert not self.context.regions_entered[USER] # Now sending a location update moves me again. self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE) @@ -749,7 +749,7 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.send_message(EVENT_TOPIC, message) # Left clean zone state - self.assertFalse(self.context.regions_entered[USER]) + assert not self.context.regions_entered[USER] def test_event_region_entry_exit_right_order(self): """Test the event for ordering.""" @@ -959,8 +959,8 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.hass.block_till_done() self.send_message(EVENT_TOPIC, MOBILE_BEACON_LEAVE_EVENT_MESSAGE) - self.assertEqual(len(self.context.mobile_beacons_active['greg_phone']), - 0) + assert len(self.context.mobile_beacons_active['greg_phone']) == \ + 0 def test_mobile_multiple_enter_exit(self): """Test the multiple entering.""" @@ -968,8 +968,8 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.send_message(EVENT_TOPIC, MOBILE_BEACON_ENTER_EVENT_MESSAGE) self.send_message(EVENT_TOPIC, MOBILE_BEACON_LEAVE_EVENT_MESSAGE) - self.assertEqual(len(self.context.mobile_beacons_active['greg_phone']), - 0) + assert len(self.context.mobile_beacons_active['greg_phone']) == \ + 0 def test_complex_movement(self): """Test a complex sequence representative of real-world use.""" @@ -1168,9 +1168,9 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.send_message(WAYPOINTS_TOPIC, waypoints_message) # Check if it made it into states wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[0]) - self.assertTrue(wayp is not None) + assert wayp is not None wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[1]) - self.assertTrue(wayp is not None) + assert wayp is not None def test_waypoint_import_blacklist(self): """Test import of list of waypoints for blacklisted user.""" @@ -1178,9 +1178,9 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.send_message(WAYPOINTS_TOPIC_BLOCKED, waypoints_message) # Check if it made it into states wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[2]) - self.assertTrue(wayp is None) + assert wayp is None wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[3]) - self.assertTrue(wayp is None) + assert wayp is None def test_waypoint_import_no_whitelist(self): """Test import of list of waypoints with no whitelist set.""" @@ -1201,9 +1201,9 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.send_message(WAYPOINTS_TOPIC_BLOCKED, waypoints_message) # Check if it made it into states wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[2]) - self.assertTrue(wayp is not None) + assert wayp is not None wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[3]) - self.assertTrue(wayp is not None) + assert wayp is not None def test_waypoint_import_bad_json(self): """Test importing a bad JSON payload.""" @@ -1211,9 +1211,9 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): self.send_message(WAYPOINTS_TOPIC, waypoints_message, True) # Check if it made it into states wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[2]) - self.assertTrue(wayp is None) + assert wayp is None wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[3]) - self.assertTrue(wayp is None) + assert wayp is None def test_waypoint_import_existing(self): """Test importing a zone that exists.""" @@ -1225,14 +1225,14 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): waypoints_message = WAYPOINTS_UPDATED_MESSAGE.copy() self.send_message(WAYPOINTS_TOPIC, waypoints_message) new_wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[0]) - self.assertTrue(wayp == new_wayp) + assert wayp == new_wayp def test_single_waypoint_import(self): """Test single waypoint message.""" waypoint_message = WAYPOINT_MESSAGE.copy() self.send_message(WAYPOINT_TOPIC, waypoint_message) wayp = self.hass.states.get(WAYPOINT_ENTITY_NAMES[0]) - self.assertTrue(wayp is not None) + assert wayp is not None def test_not_implemented_message(self): """Handle not implemented message type.""" @@ -1240,7 +1240,7 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): 'owntracks.async_handle_not_impl_msg', return_value=mock_coro(False)) patch_handler.start() - self.assertFalse(self.send_message(LWT_TOPIC, LWT_MESSAGE)) + assert not self.send_message(LWT_TOPIC, LWT_MESSAGE) patch_handler.stop() def test_unsupported_message(self): @@ -1249,7 +1249,7 @@ class TestDeviceTrackerOwnTracks(BaseMQTT): 'owntracks.async_handle_unsupported_msg', return_value=mock_coro(False)) patch_handler.start() - self.assertFalse(self.send_message(BAD_TOPIC, BAD_MESSAGE)) + assert not self.send_message(BAD_TOPIC, BAD_MESSAGE) patch_handler.stop() @@ -1465,7 +1465,7 @@ class TestDeviceTrackerOwnTrackConfigs(BaseMQTT): 'zone.inner', 'zoning', INNER_ZONE) message = build_message({'desc': 'foo'}, REGION_GPS_ENTER_MESSAGE) - self.assertEqual(message['desc'], 'foo') + assert message['desc'] == 'foo' self.send_message(EVENT_TOPIC, message) self.assert_location_state('inner') diff --git a/tests/components/device_tracker/test_tplink.py b/tests/components/device_tracker/test_tplink.py index b9f1f5f5e..b50d1c675 100644 --- a/tests/components/device_tracker/test_tplink.py +++ b/tests/components/device_tracker/test_tplink.py @@ -40,8 +40,7 @@ class TestTplink4DeviceScanner(unittest.TestCase): # Mock the token retrieval process FAKE_TOKEN = 'fake_token' fake_auth_token_response = 'window.parent.location.href = ' \ - '"https://a/{}/userRpm/Index.htm";'.format( - FAKE_TOKEN) + '"https://a/{}/userRpm/Index.htm";'.format(FAKE_TOKEN) m.get('http://{}/userRpm/LoginRpm.htm?Save=Save'.format( conf_dict[CONF_HOST]), text=fake_auth_token_response) @@ -65,4 +64,4 @@ class TestTplink4DeviceScanner(unittest.TestCase): expected_mac_results = [mac.replace('-', ':') for mac in [FAKE_MAC_1, FAKE_MAC_2, FAKE_MAC_3]] - self.assertEqual(tplink.last_results, expected_mac_results) + assert tplink.last_results == expected_mac_results diff --git a/tests/components/device_tracker/test_unifi_direct.py b/tests/components/device_tracker/test_unifi_direct.py index 1f9cbd24f..6e2830eee 100644 --- a/tests/components/device_tracker/test_unifi_direct.py +++ b/tests/components/device_tracker/test_unifi_direct.py @@ -66,7 +66,7 @@ class TestComponentsDeviceTrackerUnifiDirect(unittest.TestCase): assert setup_component(self.hass, DOMAIN, conf_dict) conf_dict[DOMAIN][CONF_PORT] = 22 - self.assertEqual(unifi_mock.call_args, mock.call(conf_dict[DOMAIN])) + assert unifi_mock.call_args == mock.call(conf_dict[DOMAIN]) @patch('pexpect.pxssh.pxssh') def test_get_device_name(self, mock_ssh): @@ -85,11 +85,11 @@ class TestComponentsDeviceTrackerUnifiDirect(unittest.TestCase): mock_ssh.return_value.before = load_fixture('unifi_direct.txt') scanner = get_scanner(self.hass, conf_dict) devices = scanner.scan_devices() - self.assertEqual(23, len(devices)) - self.assertEqual("iPhone", - scanner.get_device_name("98:00:c6:56:34:12")) - self.assertEqual("iPhone", - scanner.get_device_name("98:00:C6:56:34:12")) + assert 23 == len(devices) + assert "iPhone" == \ + scanner.get_device_name("98:00:c6:56:34:12") + assert "iPhone" == \ + scanner.get_device_name("98:00:C6:56:34:12") @patch('pexpect.pxssh.pxssh.logout') @patch('pexpect.pxssh.pxssh.login') @@ -111,7 +111,7 @@ class TestComponentsDeviceTrackerUnifiDirect(unittest.TestCase): mock_login.side_effect = exceptions.EOF("Test") scanner = get_scanner(self.hass, conf_dict) - self.assertFalse(scanner) + assert not scanner @patch('pexpect.pxssh.pxssh.logout') @patch('pexpect.pxssh.pxssh.login', autospec=True) @@ -136,16 +136,16 @@ class TestComponentsDeviceTrackerUnifiDirect(unittest.TestCase): # mock_sendline.side_effect = AssertionError("Test") mock_prompt.side_effect = AssertionError("Test") devices = scanner._get_update() # pylint: disable=protected-access - self.assertTrue(devices is None) + assert devices is None def test_good_response_parses(self): """Test that the response form the AP parses to JSON correctly.""" response = _response_to_json(load_fixture('unifi_direct.txt')) - self.assertTrue(response != {}) + assert response != {} def test_bad_response_returns_none(self): """Test that a bad response form the AP parses to JSON correctly.""" - self.assertTrue(_response_to_json("{(}") == {}) + assert _response_to_json("{(}") == {} def test_config_error(): diff --git a/tests/components/device_tracker/test_xiaomi.py b/tests/components/device_tracker/test_xiaomi.py index 0705fb2c3..9c7c13ee7 100644 --- a/tests/components/device_tracker/test_xiaomi.py +++ b/tests/components/device_tracker/test_xiaomi.py @@ -176,13 +176,13 @@ class TestXiaomiDeviceScanner(unittest.TestCase): }) } xiaomi.get_scanner(self.hass, config) - self.assertEqual(xiaomi_mock.call_count, 1) - self.assertEqual(xiaomi_mock.call_args, mock.call(config[DOMAIN])) + assert xiaomi_mock.call_count == 1 + assert xiaomi_mock.call_args == mock.call(config[DOMAIN]) call_arg = xiaomi_mock.call_args[0][0] - self.assertEqual(call_arg['username'], 'admin') - self.assertEqual(call_arg['password'], 'passwordTest') - self.assertEqual(call_arg['host'], '192.168.0.1') - self.assertEqual(call_arg['platform'], 'device_tracker') + assert call_arg['username'] == 'admin' + assert call_arg['password'] == 'passwordTest' + assert call_arg['host'] == '192.168.0.1' + assert call_arg['platform'] == 'device_tracker' @mock.patch( 'homeassistant.components.device_tracker.xiaomi.XiaomiDeviceScanner', @@ -198,13 +198,13 @@ class TestXiaomiDeviceScanner(unittest.TestCase): }) } xiaomi.get_scanner(self.hass, config) - self.assertEqual(xiaomi_mock.call_count, 1) - self.assertEqual(xiaomi_mock.call_args, mock.call(config[DOMAIN])) + assert xiaomi_mock.call_count == 1 + assert xiaomi_mock.call_args == mock.call(config[DOMAIN]) call_arg = xiaomi_mock.call_args[0][0] - self.assertEqual(call_arg['username'], 'alternativeAdminName') - self.assertEqual(call_arg['password'], 'passwordTest') - self.assertEqual(call_arg['host'], '192.168.0.1') - self.assertEqual(call_arg['platform'], 'device_tracker') + assert call_arg['username'] == 'alternativeAdminName' + assert call_arg['password'] == 'passwordTest' + assert call_arg['host'] == '192.168.0.1' + assert call_arg['platform'] == 'device_tracker' @patch('requests.get', side_effect=mocked_requests) @patch('requests.post', side_effect=mocked_requests) @@ -218,7 +218,7 @@ class TestXiaomiDeviceScanner(unittest.TestCase): CONF_PASSWORD: 'passwordTest' }) } - self.assertIsNone(get_scanner(self.hass, config)) + assert get_scanner(self.hass, config) is None @patch('requests.get', side_effect=mocked_requests) @patch('requests.post', side_effect=mocked_requests) @@ -233,12 +233,12 @@ class TestXiaomiDeviceScanner(unittest.TestCase): }) } scanner = get_scanner(self.hass, config) - self.assertIsNotNone(scanner) - self.assertEqual(2, len(scanner.scan_devices())) - self.assertEqual("Device1", - scanner.get_device_name("23:83:BF:F6:38:A0")) - self.assertEqual("Device2", - scanner.get_device_name("1D:98:EC:5E:D5:A6")) + assert scanner is not None + assert 2 == len(scanner.scan_devices()) + assert "Device1" == \ + scanner.get_device_name("23:83:BF:F6:38:A0") + assert "Device2" == \ + scanner.get_device_name("1D:98:EC:5E:D5:A6") @patch('requests.get', side_effect=mocked_requests) @patch('requests.post', side_effect=mocked_requests) @@ -256,9 +256,9 @@ class TestXiaomiDeviceScanner(unittest.TestCase): }) } scanner = get_scanner(self.hass, config) - self.assertIsNotNone(scanner) - self.assertEqual(2, len(scanner.scan_devices())) - self.assertEqual("Device1", - scanner.get_device_name("23:83:BF:F6:38:A0")) - self.assertEqual("Device2", - scanner.get_device_name("1D:98:EC:5E:D5:A6")) + assert scanner is not None + assert 2 == len(scanner.scan_devices()) + assert "Device1" == \ + scanner.get_device_name("23:83:BF:F6:38:A0") + assert "Device2" == \ + scanner.get_device_name("1D:98:EC:5E:D5:A6") diff --git a/tests/components/emulated_hue/test_upnp.py b/tests/components/emulated_hue/test_upnp.py index f5377b181..9c549f00e 100644 --- a/tests/components/emulated_hue/test_upnp.py +++ b/tests/components/emulated_hue/test_upnp.py @@ -83,8 +83,8 @@ class TestEmulatedHue(unittest.TestCase): result = requests.get( BRIDGE_URL_BASE.format('/description.xml'), timeout=5) - self.assertEqual(result.status_code, 200) - self.assertTrue('text/xml' in result.headers['content-type']) + assert result.status_code == 200 + assert 'text/xml' in result.headers['content-type'] # Make sure the XML is parsable try: @@ -100,14 +100,14 @@ class TestEmulatedHue(unittest.TestCase): BRIDGE_URL_BASE.format('/api'), data=json.dumps(request_json), timeout=5) - self.assertEqual(result.status_code, 200) - self.assertTrue('application/json' in result.headers['content-type']) + assert result.status_code == 200 + assert 'application/json' in result.headers['content-type'] resp_json = result.json() success_json = resp_json[0] - self.assertTrue('success' in success_json) - self.assertTrue('username' in success_json['success']) + assert 'success' in success_json + assert 'username' in success_json['success'] def test_valid_username_request(self): """Test request with a valid username.""" @@ -117,4 +117,4 @@ class TestEmulatedHue(unittest.TestCase): BRIDGE_URL_BASE.format('/api'), data=json.dumps(request_json), timeout=5) - self.assertEqual(result.status_code, 400) + assert result.status_code == 400 diff --git a/tests/components/fan/test_demo.py b/tests/components/fan/test_demo.py index 48704ca44..35835ac37 100644 --- a/tests/components/fan/test_demo.py +++ b/tests/components/fan/test_demo.py @@ -22,9 +22,9 @@ class TestDemoFan(unittest.TestCase): def setUp(self): """Initialize unit test data.""" self.hass = get_test_home_assistant() - self.assertTrue(setup_component(self.hass, fan.DOMAIN, {'fan': { + assert setup_component(self.hass, fan.DOMAIN, {'fan': { 'platform': 'demo', - }})) + }}) self.hass.block_till_done() def tearDown(self): @@ -33,76 +33,76 @@ class TestDemoFan(unittest.TestCase): def test_turn_on(self): """Test turning on the device.""" - self.assertEqual(STATE_OFF, self.get_entity().state) + assert STATE_OFF == self.get_entity().state common.turn_on(self.hass, FAN_ENTITY_ID) self.hass.block_till_done() - self.assertNotEqual(STATE_OFF, self.get_entity().state) + assert STATE_OFF != self.get_entity().state common.turn_on(self.hass, FAN_ENTITY_ID, fan.SPEED_HIGH) self.hass.block_till_done() - self.assertEqual(STATE_ON, self.get_entity().state) - self.assertEqual(fan.SPEED_HIGH, - self.get_entity().attributes[fan.ATTR_SPEED]) + assert STATE_ON == self.get_entity().state + assert fan.SPEED_HIGH == \ + self.get_entity().attributes[fan.ATTR_SPEED] def test_turn_off(self): """Test turning off the device.""" - self.assertEqual(STATE_OFF, self.get_entity().state) + assert STATE_OFF == self.get_entity().state common.turn_on(self.hass, FAN_ENTITY_ID) self.hass.block_till_done() - self.assertNotEqual(STATE_OFF, self.get_entity().state) + assert STATE_OFF != self.get_entity().state common.turn_off(self.hass, FAN_ENTITY_ID) self.hass.block_till_done() - self.assertEqual(STATE_OFF, self.get_entity().state) + assert STATE_OFF == self.get_entity().state def test_turn_off_without_entity_id(self): """Test turning off all fans.""" - self.assertEqual(STATE_OFF, self.get_entity().state) + assert STATE_OFF == self.get_entity().state common.turn_on(self.hass, FAN_ENTITY_ID) self.hass.block_till_done() - self.assertNotEqual(STATE_OFF, self.get_entity().state) + assert STATE_OFF != self.get_entity().state common.turn_off(self.hass) self.hass.block_till_done() - self.assertEqual(STATE_OFF, self.get_entity().state) + assert STATE_OFF == self.get_entity().state def test_set_direction(self): """Test setting the direction of the device.""" - self.assertEqual(STATE_OFF, self.get_entity().state) + assert STATE_OFF == self.get_entity().state common.set_direction(self.hass, FAN_ENTITY_ID, fan.DIRECTION_REVERSE) self.hass.block_till_done() - self.assertEqual(fan.DIRECTION_REVERSE, - self.get_entity().attributes.get('direction')) + assert fan.DIRECTION_REVERSE == \ + self.get_entity().attributes.get('direction') def test_set_speed(self): """Test setting the speed of the device.""" - self.assertEqual(STATE_OFF, self.get_entity().state) + assert STATE_OFF == self.get_entity().state common.set_speed(self.hass, FAN_ENTITY_ID, fan.SPEED_LOW) self.hass.block_till_done() - self.assertEqual(fan.SPEED_LOW, - self.get_entity().attributes.get('speed')) + assert fan.SPEED_LOW == \ + self.get_entity().attributes.get('speed') def test_oscillate(self): """Test oscillating the fan.""" - self.assertFalse(self.get_entity().attributes.get('oscillating')) + assert not self.get_entity().attributes.get('oscillating') common.oscillate(self.hass, FAN_ENTITY_ID, True) self.hass.block_till_done() - self.assertTrue(self.get_entity().attributes.get('oscillating')) + assert self.get_entity().attributes.get('oscillating') common.oscillate(self.hass, FAN_ENTITY_ID, False) self.hass.block_till_done() - self.assertFalse(self.get_entity().attributes.get('oscillating')) + assert not self.get_entity().attributes.get('oscillating') def test_is_on(self): """Test is on service call.""" - self.assertFalse(fan.is_on(self.hass, FAN_ENTITY_ID)) + assert not fan.is_on(self.hass, FAN_ENTITY_ID) common.turn_on(self.hass, FAN_ENTITY_ID) self.hass.block_till_done() - self.assertTrue(fan.is_on(self.hass, FAN_ENTITY_ID)) + assert fan.is_on(self.hass, FAN_ENTITY_ID) diff --git a/tests/components/fan/test_dyson.py b/tests/components/fan/test_dyson.py index 452f8e199..aacab700f 100644 --- a/tests/components/fan/test_dyson.py +++ b/tests/components/fan/test_dyson.py @@ -130,14 +130,14 @@ class DysonTest(unittest.TestCase): } }) self.hass.block_till_done() - self.assertEqual(len(self.hass.data[dyson.DYSON_DEVICES]), 1) + assert len(self.hass.data[dyson.DYSON_DEVICES]) == 1 assert mocked_devices.return_value[0].add_message_listener.called def test_dyson_set_speed(self): """Test set fan speed.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertFalse(component.should_poll) + assert not component.should_poll component.set_speed("1") set_config = device.set_configuration set_config.assert_called_with(fan_mode=FanMode.FAN, @@ -151,7 +151,7 @@ class DysonTest(unittest.TestCase): """Test turn on fan.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertFalse(component.should_poll) + assert not component.should_poll component.turn_on() set_config = device.set_configuration set_config.assert_called_with(fan_mode=FanMode.FAN) @@ -160,7 +160,7 @@ class DysonTest(unittest.TestCase): """Test turn on fan with night mode.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertFalse(component.should_poll) + assert not component.should_poll component.night_mode(True) set_config = device.set_configuration set_config.assert_called_with(night_mode=NightMode.NIGHT_MODE_ON) @@ -173,17 +173,17 @@ class DysonTest(unittest.TestCase): """Test night mode.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertFalse(component.is_night_mode) + assert not component.is_night_mode device = _get_device_off() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertTrue(component.is_night_mode) + assert component.is_night_mode def test_dyson_turn_auto_mode(self): """Test turn on/off fan with auto mode.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertFalse(component.should_poll) + assert not component.should_poll component.auto_mode(True) set_config = device.set_configuration set_config.assert_called_with(fan_mode=FanMode.AUTO) @@ -196,17 +196,17 @@ class DysonTest(unittest.TestCase): """Test auto mode.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertFalse(component.is_auto_mode) + assert not component.is_auto_mode device = _get_device_auto() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertTrue(component.is_auto_mode) + assert component.is_auto_mode def test_dyson_turn_on_speed(self): """Test turn on fan with specified speed.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertFalse(component.should_poll) + assert not component.should_poll component.turn_on("1") set_config = device.set_configuration set_config.assert_called_with(fan_mode=FanMode.FAN, @@ -220,7 +220,7 @@ class DysonTest(unittest.TestCase): """Test turn off fan.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertFalse(component.should_poll) + assert not component.should_poll component.turn_off() set_config = device.set_configuration set_config.assert_called_with(fan_mode=FanMode.OFF) @@ -245,65 +245,65 @@ class DysonTest(unittest.TestCase): """Test get oscillation value on.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertTrue(component.oscillating) + assert component.oscillating def test_dyson_oscillate_value_off(self): """Test get oscillation value off.""" device = _get_device_off() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertFalse(component.oscillating) + assert not component.oscillating def test_dyson_on(self): """Test device is on.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertTrue(component.is_on) + assert component.is_on def test_dyson_off(self): """Test device is off.""" device = _get_device_off() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertFalse(component.is_on) + assert not component.is_on device = _get_device_with_no_state() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertFalse(component.is_on) + assert not component.is_on def test_dyson_get_speed(self): """Test get device speed.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertEqual(component.speed, 1) + assert component.speed == 1 device = _get_device_off() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertEqual(component.speed, 4) + assert component.speed == 4 device = _get_device_with_no_state() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertIsNone(component.speed) + assert component.speed is None device = _get_device_auto() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertEqual(component.speed, "AUTO") + assert component.speed == "AUTO" def test_dyson_get_direction(self): """Test get device direction.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertIsNone(component.current_direction) + assert component.current_direction is None def test_dyson_get_speed_list(self): """Test get speeds list.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertEqual(len(component.speed_list), 11) + assert len(component.speed_list) == 11 def test_dyson_supported_features(self): """Test supported features.""" device = _get_device_on() component = dyson.DysonPureCoolLinkDevice(self.hass, device) - self.assertEqual(component.supported_features, 3) + assert component.supported_features == 3 def test_on_message(self): """Test when message is received.""" diff --git a/tests/components/fan/test_init.py b/tests/components/fan/test_init.py index 15f9a79d2..920a2b810 100644 --- a/tests/components/fan/test_init.py +++ b/tests/components/fan/test_init.py @@ -3,6 +3,7 @@ import unittest from homeassistant.components.fan import FanEntity +import pytest class BaseFan(FanEntity): @@ -26,15 +27,15 @@ class TestFanEntity(unittest.TestCase): def test_fanentity(self): """Test fan entity methods.""" - self.assertEqual('on', self.fan.state) - self.assertEqual(0, len(self.fan.speed_list)) - self.assertEqual(0, self.fan.supported_features) - self.assertEqual({'speed_list': []}, self.fan.state_attributes) + assert 'on' == self.fan.state + assert 0 == len(self.fan.speed_list) + assert 0 == self.fan.supported_features + assert {'speed_list': []} == self.fan.state_attributes # Test set_speed not required self.fan.oscillate(True) - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): self.fan.set_speed('slow') - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): self.fan.turn_on() - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): self.fan.turn_off() diff --git a/tests/components/fan/test_mqtt.py b/tests/components/fan/test_mqtt.py index e2742eeba..7bbb8467e 100644 --- a/tests/components/fan/test_mqtt.py +++ b/tests/components/fan/test_mqtt.py @@ -37,32 +37,32 @@ class TestMqttFan(unittest.TestCase): }) state = self.hass.states.get('fan.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability_topic', 'online') self.hass.block_till_done() state = self.hass.states.get('fan.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_UNAVAILABLE != state.state + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'availability_topic', 'offline') self.hass.block_till_done() state = self.hass.states.get('fan.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'state-topic', '1') self.hass.block_till_done() state = self.hass.states.get('fan.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability_topic', 'online') self.hass.block_till_done() state = self.hass.states.get('fan.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state def test_custom_availability_payload(self): """Test the availability payload.""" @@ -79,32 +79,32 @@ class TestMqttFan(unittest.TestCase): }) state = self.hass.states.get('fan.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability_topic', 'good') self.hass.block_till_done() state = self.hass.states.get('fan.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_UNAVAILABLE != state.state + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'availability_topic', 'nogood') self.hass.block_till_done() state = self.hass.states.get('fan.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'state-topic', '1') self.hass.block_till_done() state = self.hass.states.get('fan.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability_topic', 'good') self.hass.block_till_done() state = self.hass.states.get('fan.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state async def test_discovery_removal_fan(hass, mqtt_mock, caplog): diff --git a/tests/components/geo_location/test_demo.py b/tests/components/geo_location/test_demo.py index 158e5d619..a35a8e11a 100644 --- a/tests/components/geo_location/test_demo.py +++ b/tests/components/geo_location/test_demo.py @@ -37,8 +37,7 @@ class TestDemoPlatform(unittest.TestCase): # Patching 'utcnow' to gain more control over the timed update. with patch('homeassistant.util.dt.utcnow', return_value=utcnow): with assert_setup_component(1, geo_location.DOMAIN): - self.assertTrue(setup_component(self.hass, geo_location.DOMAIN, - CONFIG)) + assert setup_component(self.hass, geo_location.DOMAIN, CONFIG) # In this test, only entities of the geo location domain have been # generated. @@ -47,10 +46,14 @@ class TestDemoPlatform(unittest.TestCase): # Check a single device's attributes. state_first_entry = all_states[0] - self.assertAlmostEqual(state_first_entry.attributes['latitude'], - self.hass.config.latitude, delta=1.0) - self.assertAlmostEqual(state_first_entry.attributes['longitude'], - self.hass.config.longitude, delta=1.0) + assert abs( + state_first_entry.attributes['latitude'] - + self.hass.config.latitude + ) < 1.0 + assert abs( + state_first_entry.attributes['longitude'] - + self.hass.config.longitude + ) < 1.0 assert state_first_entry.attributes['unit_of_measurement'] == \ DEFAULT_UNIT_OF_MEASUREMENT # Update (replaces 1 device). @@ -60,4 +63,4 @@ class TestDemoPlatform(unittest.TestCase): # the same, but the lists are different. all_states_updated = self.hass.states.all() assert len(all_states_updated) == NUMBER_OF_DEMO_DEVICES - self.assertNotEqual(all_states, all_states_updated) + assert all_states != all_states_updated diff --git a/tests/components/geo_location/test_geo_json_events.py b/tests/components/geo_location/test_geo_json_events.py index 00fc9f8c9..f476598ad 100644 --- a/tests/components/geo_location/test_geo_json_events.py +++ b/tests/components/geo_location/test_geo_json_events.py @@ -70,8 +70,7 @@ class TestGeoJsonPlatform(unittest.TestCase): # Patching 'utcnow' to gain more control over the timed update. with patch('homeassistant.util.dt.utcnow', return_value=utcnow): with assert_setup_component(1, geo_location.DOMAIN): - self.assertTrue(setup_component(self.hass, geo_location.DOMAIN, - CONFIG)) + assert setup_component(self.hass, geo_location.DOMAIN, CONFIG) # Artificially trigger update. self.hass.bus.fire(EVENT_HOMEASSISTANT_START) # Collect events. @@ -81,34 +80,34 @@ class TestGeoJsonPlatform(unittest.TestCase): assert len(all_states) == 3 state = self.hass.states.get("geo_location.title_1") - self.assertIsNotNone(state) + assert state is not None assert state.name == "Title 1" assert state.attributes == { ATTR_EXTERNAL_ID: "1234", ATTR_LATITUDE: -31.0, ATTR_LONGITUDE: 150.0, ATTR_FRIENDLY_NAME: "Title 1", ATTR_UNIT_OF_MEASUREMENT: "km", ATTR_SOURCE: 'geo_json_events'} - self.assertAlmostEqual(float(state.state), 15.5) + assert round(abs(float(state.state)-15.5), 7) == 0 state = self.hass.states.get("geo_location.title_2") - self.assertIsNotNone(state) + assert state is not None assert state.name == "Title 2" assert state.attributes == { ATTR_EXTERNAL_ID: "2345", ATTR_LATITUDE: -31.1, ATTR_LONGITUDE: 150.1, ATTR_FRIENDLY_NAME: "Title 2", ATTR_UNIT_OF_MEASUREMENT: "km", ATTR_SOURCE: 'geo_json_events'} - self.assertAlmostEqual(float(state.state), 20.5) + assert round(abs(float(state.state)-20.5), 7) == 0 state = self.hass.states.get("geo_location.title_3") - self.assertIsNotNone(state) + assert state is not None assert state.name == "Title 3" assert state.attributes == { ATTR_EXTERNAL_ID: "3456", ATTR_LATITUDE: -31.2, ATTR_LONGITUDE: 150.2, ATTR_FRIENDLY_NAME: "Title 3", ATTR_UNIT_OF_MEASUREMENT: "km", ATTR_SOURCE: 'geo_json_events'} - self.assertAlmostEqual(float(state.state), 25.5) + assert round(abs(float(state.state)-25.5), 7) == 0 # Simulate an update - one existing, one new entry, # one outdated entry @@ -162,8 +161,7 @@ class TestGeoJsonPlatform(unittest.TestCase): # Patching 'utcnow' to gain more control over the timed update. with patch('homeassistant.util.dt.utcnow', return_value=utcnow): with assert_setup_component(1, geo_location.DOMAIN): - self.assertTrue(setup_component(self.hass, geo_location.DOMAIN, - CONFIG)) + assert setup_component(self.hass, geo_location.DOMAIN, CONFIG) # This gives us the ability to assert the '_delete_callback' # has been called while still executing it. diff --git a/tests/components/geo_location/test_nsw_rural_fire_service_feed.py b/tests/components/geo_location/test_nsw_rural_fire_service_feed.py index 92c4bae19..665f60179 100644 --- a/tests/components/geo_location/test_nsw_rural_fire_service_feed.py +++ b/tests/components/geo_location/test_nsw_rural_fire_service_feed.py @@ -93,8 +93,7 @@ class TestGeoJsonPlatform(unittest.TestCase): # Patching 'utcnow' to gain more control over the timed update. with patch('homeassistant.util.dt.utcnow', return_value=utcnow): with assert_setup_component(1, geo_location.DOMAIN): - self.assertTrue(setup_component(self.hass, geo_location.DOMAIN, - CONFIG)) + assert setup_component(self.hass, geo_location.DOMAIN, CONFIG) # Artificially trigger update. self.hass.bus.fire(EVENT_HOMEASSISTANT_START) # Collect events. @@ -104,7 +103,7 @@ class TestGeoJsonPlatform(unittest.TestCase): assert len(all_states) == 3 state = self.hass.states.get("geo_location.title_1") - self.assertIsNotNone(state) + assert state is not None assert state.name == "Title 1" assert state.attributes == { ATTR_EXTERNAL_ID: "1234", ATTR_LATITUDE: -31.0, @@ -120,10 +119,10 @@ class TestGeoJsonPlatform(unittest.TestCase): ATTR_SIZE: 'Size 1', ATTR_RESPONSIBLE_AGENCY: 'Agency 1', ATTR_UNIT_OF_MEASUREMENT: "km", ATTR_SOURCE: 'nsw_rural_fire_service_feed'} - self.assertAlmostEqual(float(state.state), 15.5) + assert round(abs(float(state.state)-15.5), 7) == 0 state = self.hass.states.get("geo_location.title_2") - self.assertIsNotNone(state) + assert state is not None assert state.name == "Title 2" assert state.attributes == { ATTR_EXTERNAL_ID: "2345", ATTR_LATITUDE: -31.1, @@ -131,10 +130,10 @@ class TestGeoJsonPlatform(unittest.TestCase): ATTR_FIRE: False, ATTR_UNIT_OF_MEASUREMENT: "km", ATTR_SOURCE: 'nsw_rural_fire_service_feed'} - self.assertAlmostEqual(float(state.state), 20.5) + assert round(abs(float(state.state)-20.5), 7) == 0 state = self.hass.states.get("geo_location.title_3") - self.assertIsNotNone(state) + assert state is not None assert state.name == "Title 3" assert state.attributes == { ATTR_EXTERNAL_ID: "3456", ATTR_LATITUDE: -31.2, @@ -142,7 +141,7 @@ class TestGeoJsonPlatform(unittest.TestCase): ATTR_FIRE: True, ATTR_UNIT_OF_MEASUREMENT: "km", ATTR_SOURCE: 'nsw_rural_fire_service_feed'} - self.assertAlmostEqual(float(state.state), 25.5) + assert round(abs(float(state.state)-25.5), 7) == 0 # Simulate an update - one existing, one new entry, # one outdated entry diff --git a/tests/components/group/test_init.py b/tests/components/group/test_init.py index 104d1427d..65558aeb2 100644 --- a/tests/components/group/test_init.py +++ b/tests/components/group/test_init.py @@ -36,10 +36,9 @@ class TestComponentsGroup(unittest.TestCase): self.hass, 'person_and_light', ['light.Bowl', 'device_tracker.Paulus']) - self.assertEqual( - STATE_ON, + assert STATE_ON == \ self.hass.states.get( - group.ENTITY_ID_FORMAT.format('person_and_light')).state) + group.ENTITY_ID_FORMAT.format('person_and_light')).state def test_setup_group_with_a_non_existing_state(self): """Try to set up a group with a non existing state.""" @@ -49,7 +48,7 @@ class TestComponentsGroup(unittest.TestCase): self.hass, 'light_and_nothing', ['light.Bowl', 'non.existing']) - self.assertEqual(STATE_ON, grp.state) + assert STATE_ON == grp.state def test_setup_group_with_non_groupable_states(self): """Test setup with groups which are not groupable.""" @@ -60,13 +59,13 @@ class TestComponentsGroup(unittest.TestCase): self.hass, 'chromecasts', ['cast.living_room', 'cast.bedroom']) - self.assertEqual(STATE_UNKNOWN, grp.state) + assert STATE_UNKNOWN == grp.state def test_setup_empty_group(self): """Try to set up an empty group.""" grp = group.Group.create_group(self.hass, 'nothing', []) - self.assertEqual(STATE_UNKNOWN, grp.state) + assert STATE_UNKNOWN == grp.state def test_monitor_group(self): """Test if the group keeps track of states.""" @@ -76,11 +75,11 @@ class TestComponentsGroup(unittest.TestCase): self.hass, 'init_group', ['light.Bowl', 'light.Ceiling'], False) # Test if group setup in our init mode is ok - self.assertIn(test_group.entity_id, self.hass.states.entity_ids()) + assert test_group.entity_id in self.hass.states.entity_ids() group_state = self.hass.states.get(test_group.entity_id) - self.assertEqual(STATE_ON, group_state.state) - self.assertTrue(group_state.attributes.get(group.ATTR_AUTO)) + assert STATE_ON == group_state.state + assert group_state.attributes.get(group.ATTR_AUTO) def test_group_turns_off_if_all_off(self): """Test if turn off if the last device that was on turns off.""" @@ -92,7 +91,7 @@ class TestComponentsGroup(unittest.TestCase): self.hass.block_till_done() group_state = self.hass.states.get(test_group.entity_id) - self.assertEqual(STATE_OFF, group_state.state) + assert STATE_OFF == group_state.state def test_group_turns_on_if_all_are_off_and_one_turns_on(self): """Test if turn on if all devices were turned off and one turns on.""" @@ -106,7 +105,7 @@ class TestComponentsGroup(unittest.TestCase): self.hass.block_till_done() group_state = self.hass.states.get(test_group.entity_id) - self.assertEqual(STATE_ON, group_state.state) + assert STATE_ON == group_state.state def test_allgroup_stays_off_if_all_are_off_and_one_turns_on(self): """Group with all: true, stay off if one device turns on.""" @@ -121,7 +120,7 @@ class TestComponentsGroup(unittest.TestCase): self.hass.block_till_done() group_state = self.hass.states.get(test_group.entity_id) - self.assertEqual(STATE_OFF, group_state.state) + assert STATE_OFF == group_state.state def test_allgroup_turn_on_if_last_turns_on(self): """Group with all: true, turn on if all devices are on.""" @@ -136,7 +135,7 @@ class TestComponentsGroup(unittest.TestCase): self.hass.block_till_done() group_state = self.hass.states.get(test_group.entity_id) - self.assertEqual(STATE_ON, group_state.state) + assert STATE_ON == group_state.state def test_is_on(self): """Test is_on method.""" @@ -145,13 +144,13 @@ class TestComponentsGroup(unittest.TestCase): test_group = group.Group.create_group( self.hass, 'init_group', ['light.Bowl', 'light.Ceiling'], False) - self.assertTrue(group.is_on(self.hass, test_group.entity_id)) + assert group.is_on(self.hass, test_group.entity_id) self.hass.states.set('light.Bowl', STATE_OFF) self.hass.block_till_done() - self.assertFalse(group.is_on(self.hass, test_group.entity_id)) + assert not group.is_on(self.hass, test_group.entity_id) # Try on non existing state - self.assertFalse(group.is_on(self.hass, 'non.existing')) + assert not group.is_on(self.hass, 'non.existing') def test_expand_entity_ids(self): """Test expand_entity_ids method.""" @@ -160,9 +159,9 @@ class TestComponentsGroup(unittest.TestCase): test_group = group.Group.create_group( self.hass, 'init_group', ['light.Bowl', 'light.Ceiling'], False) - self.assertEqual(sorted(['light.ceiling', 'light.bowl']), - sorted(group.expand_entity_ids( - self.hass, [test_group.entity_id]))) + assert sorted(['light.ceiling', 'light.bowl']) == \ + sorted(group.expand_entity_ids( + self.hass, [test_group.entity_id])) def test_expand_entity_ids_does_not_return_duplicates(self): """Test that expand_entity_ids does not return duplicates.""" @@ -171,15 +170,13 @@ class TestComponentsGroup(unittest.TestCase): test_group = group.Group.create_group( self.hass, 'init_group', ['light.Bowl', 'light.Ceiling'], False) - self.assertEqual( - ['light.bowl', 'light.ceiling'], + assert ['light.bowl', 'light.ceiling'] == \ sorted(group.expand_entity_ids( - self.hass, [test_group.entity_id, 'light.Ceiling']))) + self.hass, [test_group.entity_id, 'light.Ceiling'])) - self.assertEqual( - ['light.bowl', 'light.ceiling'], + assert ['light.bowl', 'light.ceiling'] == \ sorted(group.expand_entity_ids( - self.hass, ['light.bowl', test_group.entity_id]))) + self.hass, ['light.bowl', test_group.entity_id])) def test_expand_entity_ids_recursive(self): """Test expand_entity_ids method with a group that contains itself.""" @@ -191,13 +188,13 @@ class TestComponentsGroup(unittest.TestCase): ['light.Bowl', 'light.Ceiling', 'group.init_group'], False) - self.assertEqual(sorted(['light.ceiling', 'light.bowl']), - sorted(group.expand_entity_ids( - self.hass, [test_group.entity_id]))) + assert sorted(['light.ceiling', 'light.bowl']) == \ + sorted(group.expand_entity_ids( + self.hass, [test_group.entity_id])) def test_expand_entity_ids_ignores_non_strings(self): """Test that non string elements in lists are ignored.""" - self.assertEqual([], group.expand_entity_ids(self.hass, [5, True])) + assert [] == group.expand_entity_ids(self.hass, [5, True]) def test_get_entity_ids(self): """Test get_entity_ids method.""" @@ -206,9 +203,8 @@ class TestComponentsGroup(unittest.TestCase): test_group = group.Group.create_group( self.hass, 'init_group', ['light.Bowl', 'light.Ceiling'], False) - self.assertEqual( - ['light.bowl', 'light.ceiling'], - sorted(group.get_entity_ids(self.hass, test_group.entity_id))) + assert ['light.bowl', 'light.ceiling'] == \ + sorted(group.get_entity_ids(self.hass, test_group.entity_id)) def test_get_entity_ids_with_domain_filter(self): """Test if get_entity_ids works with a domain_filter.""" @@ -217,18 +213,17 @@ class TestComponentsGroup(unittest.TestCase): mixed_group = group.Group.create_group( self.hass, 'mixed_group', ['light.Bowl', 'switch.AC'], False) - self.assertEqual( - ['switch.ac'], + assert ['switch.ac'] == \ group.get_entity_ids( - self.hass, mixed_group.entity_id, domain_filter="switch")) + self.hass, mixed_group.entity_id, domain_filter="switch") def test_get_entity_ids_with_non_existing_group_name(self): """Test get_entity_ids with a non existing group.""" - self.assertEqual([], group.get_entity_ids(self.hass, 'non_existing')) + assert [] == group.get_entity_ids(self.hass, 'non_existing') def test_get_entity_ids_with_non_group_state(self): """Test get_entity_ids with a non group state.""" - self.assertEqual([], group.get_entity_ids(self.hass, 'switch.AC')) + assert [] == group.get_entity_ids(self.hass, 'switch.AC') def test_group_being_init_before_first_tracked_state_is_set_to_on(self): """Test if the groups turn on. @@ -244,7 +239,7 @@ class TestComponentsGroup(unittest.TestCase): self.hass.block_till_done() group_state = self.hass.states.get(test_group.entity_id) - self.assertEqual(STATE_ON, group_state.state) + assert STATE_ON == group_state.state def test_group_being_init_before_first_tracked_state_is_set_to_off(self): """Test if the group turns off. @@ -260,7 +255,7 @@ class TestComponentsGroup(unittest.TestCase): self.hass.block_till_done() group_state = self.hass.states.get(test_group.entity_id) - self.assertEqual(STATE_OFF, group_state.state) + assert STATE_OFF == group_state.state def test_setup(self): """Test setup method.""" @@ -283,36 +278,36 @@ class TestComponentsGroup(unittest.TestCase): group_state = self.hass.states.get( group.ENTITY_ID_FORMAT.format('second_group')) - self.assertEqual(STATE_ON, group_state.state) - self.assertEqual(set((test_group.entity_id, 'light.bowl')), - set(group_state.attributes['entity_id'])) - self.assertIsNone(group_state.attributes.get(group.ATTR_AUTO)) - self.assertEqual('mdi:work', - group_state.attributes.get(ATTR_ICON)) - self.assertTrue(group_state.attributes.get(group.ATTR_VIEW)) - self.assertEqual('hidden', - group_state.attributes.get(group.ATTR_CONTROL)) - self.assertTrue(group_state.attributes.get(ATTR_HIDDEN)) - self.assertEqual(1, group_state.attributes.get(group.ATTR_ORDER)) + assert STATE_ON == group_state.state + assert set((test_group.entity_id, 'light.bowl')) == \ + set(group_state.attributes['entity_id']) + assert group_state.attributes.get(group.ATTR_AUTO) is None + assert 'mdi:work' == \ + group_state.attributes.get(ATTR_ICON) + assert group_state.attributes.get(group.ATTR_VIEW) + assert 'hidden' == \ + group_state.attributes.get(group.ATTR_CONTROL) + assert group_state.attributes.get(ATTR_HIDDEN) + assert 1 == group_state.attributes.get(group.ATTR_ORDER) group_state = self.hass.states.get( group.ENTITY_ID_FORMAT.format('test_group')) - self.assertEqual(STATE_UNKNOWN, group_state.state) - self.assertEqual(set(('sensor.happy', 'hello.world')), - set(group_state.attributes['entity_id'])) - self.assertIsNone(group_state.attributes.get(group.ATTR_AUTO)) - self.assertIsNone(group_state.attributes.get(ATTR_ICON)) - self.assertIsNone(group_state.attributes.get(group.ATTR_VIEW)) - self.assertIsNone(group_state.attributes.get(group.ATTR_CONTROL)) - self.assertIsNone(group_state.attributes.get(ATTR_HIDDEN)) - self.assertEqual(2, group_state.attributes.get(group.ATTR_ORDER)) + assert STATE_UNKNOWN == group_state.state + assert set(('sensor.happy', 'hello.world')) == \ + set(group_state.attributes['entity_id']) + assert group_state.attributes.get(group.ATTR_AUTO) is None + assert group_state.attributes.get(ATTR_ICON) is None + assert group_state.attributes.get(group.ATTR_VIEW) is None + assert group_state.attributes.get(group.ATTR_CONTROL) is None + assert group_state.attributes.get(ATTR_HIDDEN) is None + assert 2 == group_state.attributes.get(group.ATTR_ORDER) def test_groups_get_unique_names(self): """Two groups with same name should both have a unique entity id.""" grp1 = group.Group.create_group(self.hass, 'Je suis Charlie') grp2 = group.Group.create_group(self.hass, 'Je suis Charlie') - self.assertNotEqual(grp1.entity_id, grp2.entity_id) + assert grp1.entity_id != grp2.entity_id def test_expand_entity_ids_expands_nested_groups(self): """Test if entity ids epands to nested groups.""" @@ -323,10 +318,10 @@ class TestComponentsGroup(unittest.TestCase): group.Group.create_group( self.hass, 'group_of_groups', ['group.light', 'group.switch']) - self.assertEqual( - ['light.test_1', 'light.test_2', 'switch.test_1', 'switch.test_2'], + assert ['light.test_1', 'light.test_2', + 'switch.test_1', 'switch.test_2'] == \ sorted(group.expand_entity_ids(self.hass, - ['group.group_of_groups']))) + ['group.group_of_groups'])) def test_set_assumed_state_based_on_tracked(self): """Test assumed state.""" @@ -337,7 +332,7 @@ class TestComponentsGroup(unittest.TestCase): ['light.Bowl', 'light.Ceiling', 'sensor.no_exist']) state = self.hass.states.get(test_group.entity_id) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert not state.attributes.get(ATTR_ASSUMED_STATE) self.hass.states.set('light.Bowl', STATE_ON, { ATTR_ASSUMED_STATE: True @@ -345,13 +340,13 @@ class TestComponentsGroup(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(test_group.entity_id) - self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) + assert state.attributes.get(ATTR_ASSUMED_STATE) self.hass.states.set('light.Bowl', STATE_ON) self.hass.block_till_done() state = self.hass.states.get(test_group.entity_id) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert not state.attributes.get(ATTR_ASSUMED_STATE) def test_group_updated_after_device_tracker_zone_change(self): """Test group state when device tracker in group changes zone.""" @@ -363,9 +358,9 @@ class TestComponentsGroup(unittest.TestCase): ['device_tracker.Adam', 'device_tracker.Eve']) self.hass.states.set('device_tracker.Adam', 'cool_state_not_home') self.hass.block_till_done() - self.assertEqual(STATE_NOT_HOME, - self.hass.states.get( - group.ENTITY_ID_FORMAT.format('peeps')).state) + assert STATE_NOT_HOME == \ + self.hass.states.get( + group.ENTITY_ID_FORMAT.format('peeps')).state def test_reloading_groups(self): """Test reloading the group config.""" @@ -419,13 +414,13 @@ class TestComponentsGroup(unittest.TestCase): common.set_visibility(self.hass, group_entity_id, False) self.hass.block_till_done() group_state = self.hass.states.get(group_entity_id) - self.assertTrue(group_state.attributes.get(ATTR_HIDDEN)) + assert group_state.attributes.get(ATTR_HIDDEN) # Show it again common.set_visibility(self.hass, group_entity_id, True) self.hass.block_till_done() group_state = self.hass.states.get(group_entity_id) - self.assertIsNone(group_state.attributes.get(ATTR_HIDDEN)) + assert group_state.attributes.get(ATTR_HIDDEN) is None def test_modify_group(self): """Test modifying a group.""" diff --git a/tests/components/light/test_init.py b/tests/components/light/test_init.py index 6253de8cb..a04fb8539 100644 --- a/tests/components/light/test_init.py +++ b/tests/components/light/test_init.py @@ -40,16 +40,16 @@ class TestLight(unittest.TestCase): """Test if methods call the services as expected.""" # Test is_on self.hass.states.set('light.test', STATE_ON) - self.assertTrue(light.is_on(self.hass, 'light.test')) + assert light.is_on(self.hass, 'light.test') self.hass.states.set('light.test', STATE_OFF) - self.assertFalse(light.is_on(self.hass, 'light.test')) + assert not light.is_on(self.hass, 'light.test') self.hass.states.set(light.ENTITY_ID_ALL_LIGHTS, STATE_ON) - self.assertTrue(light.is_on(self.hass)) + assert light.is_on(self.hass) self.hass.states.set(light.ENTITY_ID_ALL_LIGHTS, STATE_OFF) - self.assertFalse(light.is_on(self.hass)) + assert not light.is_on(self.hass) # Test turn_on turn_on_calls = mock_service( @@ -68,22 +68,19 @@ class TestLight(unittest.TestCase): self.hass.block_till_done() - self.assertEqual(1, len(turn_on_calls)) + assert 1 == len(turn_on_calls) call = turn_on_calls[-1] - self.assertEqual(light.DOMAIN, call.domain) - self.assertEqual(SERVICE_TURN_ON, call.service) - self.assertEqual('entity_id_val', call.data.get(ATTR_ENTITY_ID)) - self.assertEqual( - 'transition_val', call.data.get(light.ATTR_TRANSITION)) - self.assertEqual( - 'brightness_val', call.data.get(light.ATTR_BRIGHTNESS)) - self.assertEqual('rgb_color_val', call.data.get(light.ATTR_RGB_COLOR)) - self.assertEqual('xy_color_val', call.data.get(light.ATTR_XY_COLOR)) - self.assertEqual('profile_val', call.data.get(light.ATTR_PROFILE)) - self.assertEqual( - 'color_name_val', call.data.get(light.ATTR_COLOR_NAME)) - self.assertEqual('white_val', call.data.get(light.ATTR_WHITE_VALUE)) + assert light.DOMAIN == call.domain + assert SERVICE_TURN_ON == call.service + assert 'entity_id_val' == call.data.get(ATTR_ENTITY_ID) + assert 'transition_val' == call.data.get(light.ATTR_TRANSITION) + assert 'brightness_val' == call.data.get(light.ATTR_BRIGHTNESS) + assert 'rgb_color_val' == call.data.get(light.ATTR_RGB_COLOR) + assert 'xy_color_val' == call.data.get(light.ATTR_XY_COLOR) + assert 'profile_val' == call.data.get(light.ATTR_PROFILE) + assert 'color_name_val' == call.data.get(light.ATTR_COLOR_NAME) + assert 'white_val' == call.data.get(light.ATTR_WHITE_VALUE) # Test turn_off turn_off_calls = mock_service( @@ -94,13 +91,13 @@ class TestLight(unittest.TestCase): self.hass.block_till_done() - self.assertEqual(1, len(turn_off_calls)) + assert 1 == len(turn_off_calls) call = turn_off_calls[-1] - self.assertEqual(light.DOMAIN, call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual('entity_id_val', call.data[ATTR_ENTITY_ID]) - self.assertEqual('transition_val', call.data[light.ATTR_TRANSITION]) + assert light.DOMAIN == call.domain + assert SERVICE_TURN_OFF == call.service + assert 'entity_id_val' == call.data[ATTR_ENTITY_ID] + assert 'transition_val' == call.data[light.ATTR_TRANSITION] # Test toggle toggle_calls = mock_service( @@ -111,29 +108,28 @@ class TestLight(unittest.TestCase): self.hass.block_till_done() - self.assertEqual(1, len(toggle_calls)) + assert 1 == len(toggle_calls) call = toggle_calls[-1] - self.assertEqual(light.DOMAIN, call.domain) - self.assertEqual(SERVICE_TOGGLE, call.service) - self.assertEqual('entity_id_val', call.data[ATTR_ENTITY_ID]) - self.assertEqual('transition_val', call.data[light.ATTR_TRANSITION]) + assert light.DOMAIN == call.domain + assert SERVICE_TOGGLE == call.service + assert 'entity_id_val' == call.data[ATTR_ENTITY_ID] + assert 'transition_val' == call.data[light.ATTR_TRANSITION] def test_services(self): """Test the provided services.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1, dev2, dev3 = platform.DEVICES # Test init - self.assertTrue(light.is_on(self.hass, dev1.entity_id)) - self.assertFalse(light.is_on(self.hass, dev2.entity_id)) - self.assertFalse(light.is_on(self.hass, dev3.entity_id)) + assert light.is_on(self.hass, dev1.entity_id) + assert not light.is_on(self.hass, dev2.entity_id) + assert not light.is_on(self.hass, dev3.entity_id) # Test basic turn_on, turn_off, toggle services common.turn_off(self.hass, entity_id=dev1.entity_id) @@ -141,44 +137,44 @@ class TestLight(unittest.TestCase): self.hass.block_till_done() - self.assertFalse(light.is_on(self.hass, dev1.entity_id)) - self.assertTrue(light.is_on(self.hass, dev2.entity_id)) + assert not light.is_on(self.hass, dev1.entity_id) + assert light.is_on(self.hass, dev2.entity_id) # turn on all lights common.turn_on(self.hass) self.hass.block_till_done() - self.assertTrue(light.is_on(self.hass, dev1.entity_id)) - self.assertTrue(light.is_on(self.hass, dev2.entity_id)) - self.assertTrue(light.is_on(self.hass, dev3.entity_id)) + assert light.is_on(self.hass, dev1.entity_id) + assert light.is_on(self.hass, dev2.entity_id) + assert light.is_on(self.hass, dev3.entity_id) # turn off all lights common.turn_off(self.hass) self.hass.block_till_done() - self.assertFalse(light.is_on(self.hass, dev1.entity_id)) - self.assertFalse(light.is_on(self.hass, dev2.entity_id)) - self.assertFalse(light.is_on(self.hass, dev3.entity_id)) + assert not light.is_on(self.hass, dev1.entity_id) + assert not light.is_on(self.hass, dev2.entity_id) + assert not light.is_on(self.hass, dev3.entity_id) # toggle all lights common.toggle(self.hass) self.hass.block_till_done() - self.assertTrue(light.is_on(self.hass, dev1.entity_id)) - self.assertTrue(light.is_on(self.hass, dev2.entity_id)) - self.assertTrue(light.is_on(self.hass, dev3.entity_id)) + assert light.is_on(self.hass, dev1.entity_id) + assert light.is_on(self.hass, dev2.entity_id) + assert light.is_on(self.hass, dev3.entity_id) # toggle all lights common.toggle(self.hass) self.hass.block_till_done() - self.assertFalse(light.is_on(self.hass, dev1.entity_id)) - self.assertFalse(light.is_on(self.hass, dev2.entity_id)) - self.assertFalse(light.is_on(self.hass, dev3.entity_id)) + assert not light.is_on(self.hass, dev1.entity_id) + assert not light.is_on(self.hass, dev2.entity_id) + assert not light.is_on(self.hass, dev3.entity_id) # Ensure all attributes process correctly common.turn_on(self.hass, dev1.entity_id, @@ -191,22 +187,22 @@ class TestLight(unittest.TestCase): self.hass.block_till_done() _, data = dev1.last_call('turn_on') - self.assertEqual({ + assert { light.ATTR_TRANSITION: 10, light.ATTR_BRIGHTNESS: 20, light.ATTR_HS_COLOR: (240, 100), - }, data) + } == data _, data = dev2.last_call('turn_on') - self.assertEqual({ + assert { light.ATTR_HS_COLOR: (0, 0), light.ATTR_WHITE_VALUE: 255, - }, data) + } == data _, data = dev3.last_call('turn_on') - self.assertEqual({ + assert { light.ATTR_HS_COLOR: (71.059, 100), - }, data) + } == data # One of the light profiles prof_name, prof_h, prof_s, prof_bri = 'relax', 35.932, 69.412, 144 @@ -221,16 +217,16 @@ class TestLight(unittest.TestCase): self.hass.block_till_done() _, data = dev1.last_call('turn_on') - self.assertEqual({ + assert { light.ATTR_BRIGHTNESS: prof_bri, light.ATTR_HS_COLOR: (prof_h, prof_s), - }, data) + } == data _, data = dev2.last_call('turn_on') - self.assertEqual({ + assert { light.ATTR_BRIGHTNESS: 100, light.ATTR_HS_COLOR: (prof_h, prof_s), - }, data) + } == data # Test bad data common.turn_on(self.hass) @@ -241,13 +237,13 @@ class TestLight(unittest.TestCase): self.hass.block_till_done() _, data = dev1.last_call('turn_on') - self.assertEqual({}, data) + assert {} == data _, data = dev2.last_call('turn_on') - self.assertEqual({}, data) + assert {} == data _, data = dev3.last_call('turn_on') - self.assertEqual({}, data) + assert {} == data # faulty attributes will not trigger a service call common.turn_on( @@ -263,10 +259,10 @@ class TestLight(unittest.TestCase): self.hass.block_till_done() _, data = dev1.last_call('turn_on') - self.assertEqual({}, data) + assert {} == data _, data = dev2.last_call('turn_on') - self.assertEqual({}, data) + assert {} == data def test_broken_light_profiles(self): """Test light profiles.""" @@ -280,8 +276,8 @@ class TestLight(unittest.TestCase): user_file.write('id,x,y,brightness\n') user_file.write('I,WILL,NOT,WORK\n') - self.assertFalse(setup_component( - self.hass, light.DOMAIN, {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert not setup_component( + self.hass, light.DOMAIN, {light.DOMAIN: {CONF_PLATFORM: 'test'}}) def test_light_profiles(self): """Test light profiles.""" @@ -294,9 +290,9 @@ class TestLight(unittest.TestCase): user_file.write('id,x,y,brightness\n') user_file.write('test,.4,.6,100\n') - self.assertTrue(setup_component( + assert setup_component( self.hass, light.DOMAIN, {light.DOMAIN: {CONF_PLATFORM: 'test'}} - )) + ) dev1, _, _ = platform.DEVICES @@ -306,10 +302,10 @@ class TestLight(unittest.TestCase): _, data = dev1.last_call('turn_on') - self.assertEqual({ + assert { light.ATTR_HS_COLOR: (71.059, 100), light.ATTR_BRIGHTNESS: 100 - }, data) + } == data def test_default_profiles_group(self): """Test default turn-on light profile for all lights.""" @@ -335,19 +331,19 @@ class TestLight(unittest.TestCase): with mock.patch('os.path.isfile', side_effect=_mock_isfile): with mock.patch('builtins.open', side_effect=_mock_open): with mock_storage(): - self.assertTrue(setup_component( + assert setup_component( self.hass, light.DOMAIN, {light.DOMAIN: {CONF_PLATFORM: 'test'}} - )) + ) dev, _, _ = platform.DEVICES common.turn_on(self.hass, dev.entity_id) self.hass.block_till_done() _, data = dev.last_call('turn_on') - self.assertEqual({ + assert { light.ATTR_HS_COLOR: (71.059, 100), light.ATTR_BRIGHTNESS: 99 - }, data) + } == data def test_default_profiles_light(self): """Test default turn-on light profile for a specific light.""" @@ -374,20 +370,20 @@ class TestLight(unittest.TestCase): with mock.patch('os.path.isfile', side_effect=_mock_isfile): with mock.patch('builtins.open', side_effect=_mock_open): with mock_storage(): - self.assertTrue(setup_component( + assert setup_component( self.hass, light.DOMAIN, {light.DOMAIN: {CONF_PLATFORM: 'test'}} - )) + ) dev = next(filter(lambda x: x.entity_id == 'light.ceiling_2', platform.DEVICES)) common.turn_on(self.hass, dev.entity_id) self.hass.block_till_done() _, data = dev.last_call('turn_on') - self.assertEqual({ + assert { light.ATTR_HS_COLOR: (50.353, 100), light.ATTR_BRIGHTNESS: 100 - }, data) + } == data async def test_intent_set_color(hass): diff --git a/tests/components/light/test_mochad.py b/tests/components/light/test_mochad.py index fa122777c..d96bf8f5a 100644 --- a/tests/components/light/test_mochad.py +++ b/tests/components/light/test_mochad.py @@ -50,7 +50,7 @@ class TestMochadSwitchSetup(unittest.TestCase): ], } } - self.assertTrue(setup_component(self.hass, light.DOMAIN, good_config)) + assert setup_component(self.hass, light.DOMAIN, good_config) class TestMochadLight(unittest.TestCase): @@ -71,7 +71,7 @@ class TestMochadLight(unittest.TestCase): def test_name(self): """Test the name.""" - self.assertEqual('fake_light', self.light.name) + assert 'fake_light' == self.light.name def test_turn_on_with_no_brightness(self): """Test turn_on.""" diff --git a/tests/components/light/test_mqtt.py b/tests/components/light/test_mqtt.py index 5a768820e..84c863d86 100644 --- a/tests/components/light/test_mqtt.py +++ b/tests/components/light/test_mqtt.py @@ -193,7 +193,7 @@ class TestLightMQTT(unittest.TestCase): 'name': 'test', } }) - self.assertIsNone(self.hass.states.get('light.test')) + assert self.hass.states.get('light.test') is None def test_no_color_brightness_color_temp_hs_white_xy_if_no_topics(self): """Test if there is no color and brightness if no topic.""" @@ -208,25 +208,25 @@ class TestLightMQTT(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('rgb_color')) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('color_temp')) - self.assertIsNone(state.attributes.get('hs_color')) - self.assertIsNone(state.attributes.get('white_value')) - self.assertIsNone(state.attributes.get('xy_color')) + assert STATE_OFF == state.state + assert state.attributes.get('rgb_color') is None + assert state.attributes.get('brightness') is None + assert state.attributes.get('color_temp') is None + assert state.attributes.get('hs_color') is None + assert state.attributes.get('white_value') is None + assert state.attributes.get('xy_color') is None fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('rgb_color')) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('color_temp')) - self.assertIsNone(state.attributes.get('hs_color')) - self.assertIsNone(state.attributes.get('white_value')) - self.assertIsNone(state.attributes.get('xy_color')) + assert STATE_ON == state.state + assert state.attributes.get('rgb_color') is None + assert state.attributes.get('brightness') is None + assert state.attributes.get('color_temp') is None + assert state.attributes.get('hs_color') is None + assert state.attributes.get('white_value') is None + assert state.attributes.get('xy_color') is None def test_controlling_state_via_topic(self): """Test the controlling of the state via topic.""" @@ -258,34 +258,34 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('rgb_color')) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('color_temp')) - self.assertIsNone(state.attributes.get('effect')) - self.assertIsNone(state.attributes.get('hs_color')) - self.assertIsNone(state.attributes.get('white_value')) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert state.attributes.get('rgb_color') is None + assert state.attributes.get('brightness') is None + assert state.attributes.get('color_temp') is None + assert state.attributes.get('effect') is None + assert state.attributes.get('hs_color') is None + assert state.attributes.get('white_value') is None + assert state.attributes.get('xy_color') is None + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'test_light_rgb/status', '1') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual((255, 255, 255), state.attributes.get('rgb_color')) - self.assertEqual(255, state.attributes.get('brightness')) - self.assertEqual(150, state.attributes.get('color_temp')) - self.assertEqual('none', state.attributes.get('effect')) - self.assertEqual((0, 0), state.attributes.get('hs_color')) - self.assertEqual(255, state.attributes.get('white_value')) - self.assertEqual((0.323, 0.329), state.attributes.get('xy_color')) + assert STATE_ON == state.state + assert (255, 255, 255) == state.attributes.get('rgb_color') + assert 255 == state.attributes.get('brightness') + assert 150 == state.attributes.get('color_temp') + assert 'none' == state.attributes.get('effect') + assert (0, 0) == state.attributes.get('hs_color') + assert 255 == state.attributes.get('white_value') + assert (0.323, 0.329) == state.attributes.get('xy_color') fire_mqtt_message(self.hass, 'test_light_rgb/status', '0') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state fire_mqtt_message(self.hass, 'test_light_rgb/status', '1') self.hass.block_till_done() @@ -295,20 +295,20 @@ class TestLightMQTT(unittest.TestCase): light_state = self.hass.states.get('light.test') self.hass.block_till_done() - self.assertEqual(100, - light_state.attributes['brightness']) + assert 100 == \ + light_state.attributes['brightness'] fire_mqtt_message(self.hass, 'test_light_rgb/color_temp/status', '300') self.hass.block_till_done() light_state = self.hass.states.get('light.test') self.hass.block_till_done() - self.assertEqual(300, light_state.attributes['color_temp']) + assert 300 == light_state.attributes['color_temp'] fire_mqtt_message(self.hass, 'test_light_rgb/effect/status', 'rainbow') self.hass.block_till_done() light_state = self.hass.states.get('light.test') self.hass.block_till_done() - self.assertEqual('rainbow', light_state.attributes['effect']) + assert 'rainbow' == light_state.attributes['effect'] fire_mqtt_message(self.hass, 'test_light_rgb/white_value/status', '100') @@ -316,8 +316,8 @@ class TestLightMQTT(unittest.TestCase): light_state = self.hass.states.get('light.test') self.hass.block_till_done() - self.assertEqual(100, - light_state.attributes['white_value']) + assert 100 == \ + light_state.attributes['white_value'] fire_mqtt_message(self.hass, 'test_light_rgb/status', '1') self.hass.block_till_done() @@ -327,24 +327,24 @@ class TestLightMQTT(unittest.TestCase): self.hass.block_till_done() light_state = self.hass.states.get('light.test') - self.assertEqual((255, 255, 255), - light_state.attributes.get('rgb_color')) + assert (255, 255, 255) == \ + light_state.attributes.get('rgb_color') fire_mqtt_message(self.hass, 'test_light_rgb/hs/status', '200,50') self.hass.block_till_done() light_state = self.hass.states.get('light.test') - self.assertEqual((200, 50), - light_state.attributes.get('hs_color')) + assert (200, 50) == \ + light_state.attributes.get('hs_color') fire_mqtt_message(self.hass, 'test_light_rgb/xy/status', '0.675,0.322') self.hass.block_till_done() light_state = self.hass.states.get('light.test') - self.assertEqual((0.672, 0.324), - light_state.attributes.get('xy_color')) + assert (0.672, 0.324) == \ + light_state.attributes.get('xy_color') def test_brightness_controlling_scale(self): """Test the brightness controlling scale.""" @@ -365,22 +365,22 @@ class TestLightMQTT(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('brightness')) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert state.attributes.get('brightness') is None + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'test_scale/status', 'on') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(255, state.attributes.get('brightness')) + assert STATE_ON == state.state + assert 255 == state.attributes.get('brightness') fire_mqtt_message(self.hass, 'test_scale/status', 'off') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state fire_mqtt_message(self.hass, 'test_scale/status', 'on') self.hass.block_till_done() @@ -390,8 +390,8 @@ class TestLightMQTT(unittest.TestCase): light_state = self.hass.states.get('light.test') self.hass.block_till_done() - self.assertEqual(255, - light_state.attributes['brightness']) + assert 255 == \ + light_state.attributes['brightness'] def test_brightness_from_rgb_controlling_scale(self): """Test the brightness controlling scale.""" @@ -411,22 +411,22 @@ class TestLightMQTT(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('brightness')) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert state.attributes.get('brightness') is None + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'test_scale_rgb/status', 'on') fire_mqtt_message(self.hass, 'test_scale_rgb/rgb/status', '255,0,0') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(255, state.attributes.get('brightness')) + assert 255 == state.attributes.get('brightness') fire_mqtt_message(self.hass, 'test_scale_rgb/rgb/status', '127,0,0') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(127, state.attributes.get('brightness')) + assert 127 == state.attributes.get('brightness') def test_white_value_controlling_scale(self): """Test the white_value controlling scale.""" @@ -447,22 +447,22 @@ class TestLightMQTT(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('white_value')) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert state.attributes.get('white_value') is None + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'test_scale/status', 'on') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(255, state.attributes.get('white_value')) + assert STATE_ON == state.state + assert 255 == state.attributes.get('white_value') fire_mqtt_message(self.hass, 'test_scale/status', 'off') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state fire_mqtt_message(self.hass, 'test_scale/status', 'on') self.hass.block_till_done() @@ -472,8 +472,8 @@ class TestLightMQTT(unittest.TestCase): light_state = self.hass.states.get('light.test') self.hass.block_till_done() - self.assertEqual(255, - light_state.attributes['white_value']) + assert 255 == \ + light_state.attributes['white_value'] def test_controlling_state_via_topic_with_templates(self): """Test the setting of the state with a template.""" @@ -510,9 +510,9 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('rgb_color')) + assert STATE_OFF == state.state + assert state.attributes.get('brightness') is None + assert state.attributes.get('rgb_color') is None fire_mqtt_message(self.hass, 'test_light_rgb/rgb/status', '{"hello": [1, 2, 3]}') @@ -529,26 +529,26 @@ class TestLightMQTT(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(50, state.attributes.get('brightness')) - self.assertEqual((84, 169, 255), state.attributes.get('rgb_color')) - self.assertEqual(300, state.attributes.get('color_temp')) - self.assertEqual('rainbow', state.attributes.get('effect')) - self.assertEqual(75, state.attributes.get('white_value')) + assert STATE_ON == state.state + assert 50 == state.attributes.get('brightness') + assert (84, 169, 255) == state.attributes.get('rgb_color') + assert 300 == state.attributes.get('color_temp') + assert 'rainbow' == state.attributes.get('effect') + assert 75 == state.attributes.get('white_value') fire_mqtt_message(self.hass, 'test_light_rgb/hs/status', '{"hello": [100,50]}') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual((100, 50), state.attributes.get('hs_color')) + assert (100, 50) == state.attributes.get('hs_color') fire_mqtt_message(self.hass, 'test_light_rgb/xy/status', '{"hello": [0.123,0.123]}') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual((0.14, 0.131), state.attributes.get('xy_color')) + assert (0.14, 0.131) == state.attributes.get('xy_color') def test_sending_mqtt_commands_and_optimistic(self): """Test the sending of command in optimistic mode.""" @@ -579,13 +579,13 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(95, state.attributes.get('brightness')) - self.assertEqual((100, 100), state.attributes.get('hs_color')) - self.assertEqual('random', state.attributes.get('effect')) - self.assertEqual(100, state.attributes.get('color_temp')) - self.assertEqual(50, state.attributes.get('white_value')) - self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_ON == state.state + assert 95 == state.attributes.get('brightness') + assert (100, 100) == state.attributes.get('hs_color') + assert 'random' == state.attributes.get('effect') + assert 100 == state.attributes.get('color_temp') + assert 50 == state.attributes.get('white_value') + assert state.attributes.get(ATTR_ASSUMED_STATE) common.turn_on(self.hass, 'light.test') self.hass.block_till_done() @@ -594,7 +594,7 @@ class TestLightMQTT(unittest.TestCase): 'test_light_rgb/set', 'on', 2, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state common.turn_off(self.hass, 'light.test') self.hass.block_till_done() @@ -603,7 +603,7 @@ class TestLightMQTT(unittest.TestCase): 'test_light_rgb/set', 'off', 2, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state self.mock_publish.reset_mock() common.turn_on(self.hass, 'light.test', @@ -624,12 +624,12 @@ class TestLightMQTT(unittest.TestCase): ], any_order=True) state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual((255, 128, 0), state.attributes['rgb_color']) - self.assertEqual(50, state.attributes['brightness']) - self.assertEqual((30.118, 100), state.attributes['hs_color']) - self.assertEqual(80, state.attributes['white_value']) - self.assertEqual((0.611, 0.375), state.attributes['xy_color']) + assert STATE_ON == state.state + assert (255, 128, 0) == state.attributes['rgb_color'] + assert 50 == state.attributes['brightness'] + assert (30.118, 100) == state.attributes['hs_color'] + assert 80 == state.attributes['white_value'] + assert (0.611, 0.375) == state.attributes['xy_color'] def test_sending_mqtt_rgb_command_with_template(self): """Test the sending of RGB command with template.""" @@ -649,7 +649,7 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state common.turn_on(self.hass, 'light.test', rgb_color=[255, 128, 64]) self.hass.block_till_done() @@ -660,8 +660,8 @@ class TestLightMQTT(unittest.TestCase): ], any_order=True) state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual((255, 128, 63), state.attributes['rgb_color']) + assert STATE_ON == state.state + assert (255, 128, 63) == state.attributes['rgb_color'] def test_show_brightness_if_only_command_topic(self): """Test the brightness if only a command topic is present.""" @@ -677,15 +677,15 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_OFF == state.state + assert state.attributes.get('brightness') is None fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(255, state.attributes.get('brightness')) + assert STATE_ON == state.state + assert 255 == state.attributes.get('brightness') def test_show_color_temp_only_if_command_topic(self): """Test the color temp only if a command topic is present.""" @@ -701,15 +701,15 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('color_temp')) + assert STATE_OFF == state.state + assert state.attributes.get('color_temp') is None fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(150, state.attributes.get('color_temp')) + assert STATE_ON == state.state + assert 150 == state.attributes.get('color_temp') def test_show_effect_only_if_command_topic(self): """Test the color temp only if a command topic is present.""" @@ -725,15 +725,15 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('effect')) + assert STATE_OFF == state.state + assert state.attributes.get('effect') is None fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual('none', state.attributes.get('effect')) + assert STATE_ON == state.state + assert 'none' == state.attributes.get('effect') def test_show_hs_if_only_command_topic(self): """Test the hs if only a command topic is present.""" @@ -749,15 +749,15 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('hs_color')) + assert STATE_OFF == state.state + assert state.attributes.get('hs_color') is None fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual((0, 0), state.attributes.get('hs_color')) + assert STATE_ON == state.state + assert (0, 0) == state.attributes.get('hs_color') def test_show_white_value_if_only_command_topic(self): """Test the white_value if only a command topic is present.""" @@ -773,15 +773,15 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('white_value')) + assert STATE_OFF == state.state + assert state.attributes.get('white_value') is None fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(255, state.attributes.get('white_value')) + assert STATE_ON == state.state + assert 255 == state.attributes.get('white_value') def test_show_xy_if_only_command_topic(self): """Test the xy if only a command topic is present.""" @@ -797,15 +797,15 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('xy_color')) + assert STATE_OFF == state.state + assert state.attributes.get('xy_color') is None fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual((0.323, 0.329), state.attributes.get('xy_color')) + assert STATE_ON == state.state + assert (0.323, 0.329) == state.attributes.get('xy_color') def test_on_command_first(self): """Test on command being sent before brightness.""" @@ -821,7 +821,7 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state common.turn_on(self.hass, 'light.test', brightness=50) self.hass.block_till_done() @@ -854,7 +854,7 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state common.turn_on(self.hass, 'light.test', brightness=50) self.hass.block_till_done() @@ -889,7 +889,7 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state # Turn on w/ no brightness - should set to max common.turn_on(self.hass, 'light.test') @@ -942,7 +942,7 @@ class TestLightMQTT(unittest.TestCase): assert setup_component(self.hass, light.DOMAIN, config) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state common.turn_on(self.hass, 'light.test', brightness=127) self.hass.block_till_done() @@ -964,7 +964,7 @@ class TestLightMQTT(unittest.TestCase): def test_default_availability_payload(self): """Test availability by default payload with defined topic.""" - self.assertTrue(setup_component(self.hass, light.DOMAIN, { + assert setup_component(self.hass, light.DOMAIN, { light.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -973,26 +973,26 @@ class TestLightMQTT(unittest.TestCase): 'rgb_command_topic': "test_light/rgb", 'availability_topic': 'availability-topic' } - })) + }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'online') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'offline') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def test_custom_availability_payload(self): """Test availability by custom payload with defined topic.""" - self.assertTrue(setup_component(self.hass, light.DOMAIN, { + assert setup_component(self.hass, light.DOMAIN, { light.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -1003,22 +1003,22 @@ class TestLightMQTT(unittest.TestCase): 'payload_available': 'good', 'payload_not_available': 'nogood' } - })) + }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'good') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'nogood') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state async def test_discovery_removal_light(hass, mqtt_mock, caplog): diff --git a/tests/components/light/test_mqtt_json.py b/tests/components/light/test_mqtt_json.py index 46db2f61f..9a8d4ce73 100644 --- a/tests/components/light/test_mqtt_json.py +++ b/tests/components/light/test_mqtt_json.py @@ -127,7 +127,7 @@ class TestLightMQTTJSON(unittest.TestCase): 'name': 'test', } }) - self.assertIsNone(self.hass.states.get('light.test')) + assert self.hass.states.get('light.test') is None def test_no_color_brightness_color_temp_white_val_if_no_topics(self): """Test for no RGB, brightness, color temp, effect, white val or XY.""" @@ -141,28 +141,28 @@ class TestLightMQTTJSON(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertEqual(40, state.attributes.get(ATTR_SUPPORTED_FEATURES)) - self.assertIsNone(state.attributes.get('rgb_color')) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('color_temp')) - self.assertIsNone(state.attributes.get('effect')) - self.assertIsNone(state.attributes.get('white_value')) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('hs_color')) + assert STATE_OFF == state.state + assert 40 == state.attributes.get(ATTR_SUPPORTED_FEATURES) + assert state.attributes.get('rgb_color') is None + assert state.attributes.get('brightness') is None + assert state.attributes.get('color_temp') is None + assert state.attributes.get('effect') is None + assert state.attributes.get('white_value') is None + assert state.attributes.get('xy_color') is None + assert state.attributes.get('hs_color') is None fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"ON"}') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('rgb_color')) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('color_temp')) - self.assertIsNone(state.attributes.get('effect')) - self.assertIsNone(state.attributes.get('white_value')) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('hs_color')) + assert STATE_ON == state.state + assert state.attributes.get('rgb_color') is None + assert state.attributes.get('brightness') is None + assert state.attributes.get('color_temp') is None + assert state.attributes.get('effect') is None + assert state.attributes.get('white_value') is None + assert state.attributes.get('xy_color') is None + assert state.attributes.get('hs_color') is None def test_controlling_state_via_topic(self): """Test the controlling of the state via topic.""" @@ -184,16 +184,16 @@ class TestLightMQTTJSON(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertEqual(191, state.attributes.get(ATTR_SUPPORTED_FEATURES)) - self.assertIsNone(state.attributes.get('rgb_color')) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('color_temp')) - self.assertIsNone(state.attributes.get('effect')) - self.assertIsNone(state.attributes.get('white_value')) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('hs_color')) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert 191 == state.attributes.get(ATTR_SUPPORTED_FEATURES) + assert state.attributes.get('rgb_color') is None + assert state.attributes.get('brightness') is None + assert state.attributes.get('color_temp') is None + assert state.attributes.get('effect') is None + assert state.attributes.get('white_value') is None + assert state.attributes.get('xy_color') is None + assert state.attributes.get('hs_color') is None + assert not state.attributes.get(ATTR_ASSUMED_STATE) # Turn on the light, full white fire_mqtt_message(self.hass, 'test_light_rgb', @@ -206,21 +206,21 @@ class TestLightMQTTJSON(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual((255, 255, 255), state.attributes.get('rgb_color')) - self.assertEqual(255, state.attributes.get('brightness')) - self.assertEqual(155, state.attributes.get('color_temp')) - self.assertEqual('colorloop', state.attributes.get('effect')) - self.assertEqual(150, state.attributes.get('white_value')) - self.assertEqual((0.323, 0.329), state.attributes.get('xy_color')) - self.assertEqual((0.0, 0.0), state.attributes.get('hs_color')) + assert STATE_ON == state.state + assert (255, 255, 255) == state.attributes.get('rgb_color') + assert 255 == state.attributes.get('brightness') + assert 155 == state.attributes.get('color_temp') + assert 'colorloop' == state.attributes.get('effect') + assert 150 == state.attributes.get('white_value') + assert (0.323, 0.329) == state.attributes.get('xy_color') + assert (0.0, 0.0) == state.attributes.get('hs_color') # Turn the light off fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"OFF"}') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"ON",' @@ -229,8 +229,8 @@ class TestLightMQTTJSON(unittest.TestCase): light_state = self.hass.states.get('light.test') self.hass.block_till_done() - self.assertEqual(100, - light_state.attributes['brightness']) + assert 100 == \ + light_state.attributes['brightness'] fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"ON",' @@ -238,8 +238,8 @@ class TestLightMQTTJSON(unittest.TestCase): self.hass.block_till_done() light_state = self.hass.states.get('light.test') - self.assertEqual((255, 255, 255), - light_state.attributes.get('rgb_color')) + assert (255, 255, 255) == \ + light_state.attributes.get('rgb_color') fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"ON",' @@ -247,8 +247,8 @@ class TestLightMQTTJSON(unittest.TestCase): self.hass.block_till_done() light_state = self.hass.states.get('light.test') - self.assertEqual((0.141, 0.14), - light_state.attributes.get('xy_color')) + assert (0.141, 0.14) == \ + light_state.attributes.get('xy_color') fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"ON",' @@ -256,8 +256,8 @@ class TestLightMQTTJSON(unittest.TestCase): self.hass.block_till_done() light_state = self.hass.states.get('light.test') - self.assertEqual((180.0, 50.0), - light_state.attributes.get('hs_color')) + assert (180.0, 50.0) == \ + light_state.attributes.get('hs_color') fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"ON",' @@ -265,7 +265,7 @@ class TestLightMQTTJSON(unittest.TestCase): self.hass.block_till_done() light_state = self.hass.states.get('light.test') - self.assertEqual(155, light_state.attributes.get('color_temp')) + assert 155 == light_state.attributes.get('color_temp') fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"ON",' @@ -273,7 +273,7 @@ class TestLightMQTTJSON(unittest.TestCase): self.hass.block_till_done() light_state = self.hass.states.get('light.test') - self.assertEqual('colorloop', light_state.attributes.get('effect')) + assert 'colorloop' == light_state.attributes.get('effect') fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"ON",' @@ -281,7 +281,7 @@ class TestLightMQTTJSON(unittest.TestCase): self.hass.block_till_done() light_state = self.hass.states.get('light.test') - self.assertEqual(155, light_state.attributes.get('white_value')) + assert 155 == light_state.attributes.get('white_value') def test_sending_mqtt_commands_and_optimistic(self): """Test the sending of command in optimistic mode.""" @@ -309,14 +309,14 @@ class TestLightMQTTJSON(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(95, state.attributes.get('brightness')) - self.assertEqual((100, 100), state.attributes.get('hs_color')) - self.assertEqual('random', state.attributes.get('effect')) - self.assertEqual(100, state.attributes.get('color_temp')) - self.assertEqual(50, state.attributes.get('white_value')) - self.assertEqual(191, state.attributes.get(ATTR_SUPPORTED_FEATURES)) - self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_ON == state.state + assert 95 == state.attributes.get('brightness') + assert (100, 100) == state.attributes.get('hs_color') + assert 'random' == state.attributes.get('effect') + assert 100 == state.attributes.get('color_temp') + assert 50 == state.attributes.get('white_value') + assert 191 == state.attributes.get(ATTR_SUPPORTED_FEATURES) + assert state.attributes.get(ATTR_ASSUMED_STATE) common.turn_on(self.hass, 'light.test') self.hass.block_till_done() @@ -325,7 +325,7 @@ class TestLightMQTTJSON(unittest.TestCase): 'test_light_rgb/set', '{"state": "ON"}', 2, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state common.turn_off(self.hass, 'light.test') self.hass.block_till_done() @@ -334,61 +334,59 @@ class TestLightMQTTJSON(unittest.TestCase): 'test_light_rgb/set', '{"state": "OFF"}', 2, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state common.turn_on(self.hass, 'light.test', brightness=50, color_temp=155, effect='colorloop', white_value=170) self.hass.block_till_done() - self.assertEqual('test_light_rgb/set', - self.mock_publish.async_publish.mock_calls[0][1][0]) - self.assertEqual(2, - self.mock_publish.async_publish.mock_calls[0][1][2]) - self.assertEqual(False, - self.mock_publish.async_publish.mock_calls[0][1][3]) + assert 'test_light_rgb/set' == \ + self.mock_publish.async_publish.mock_calls[0][1][0] + assert 2 == \ + self.mock_publish.async_publish.mock_calls[0][1][2] + assert self.mock_publish.async_publish.mock_calls[0][1][3] is False # Get the sent message message_json = json.loads( self.mock_publish.async_publish.mock_calls[0][1][1]) - self.assertEqual(50, message_json["brightness"]) - self.assertEqual(155, message_json["color_temp"]) - self.assertEqual('colorloop', message_json["effect"]) - self.assertEqual(170, message_json["white_value"]) - self.assertEqual("ON", message_json["state"]) + assert 50 == message_json["brightness"] + assert 155 == message_json["color_temp"] + assert 'colorloop' == message_json["effect"] + assert 170 == message_json["white_value"] + assert "ON" == message_json["state"] state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(50, state.attributes['brightness']) - self.assertEqual(155, state.attributes['color_temp']) - self.assertEqual('colorloop', state.attributes['effect']) - self.assertEqual(170, state.attributes['white_value']) + assert STATE_ON == state.state + assert 50 == state.attributes['brightness'] + assert 155 == state.attributes['color_temp'] + assert 'colorloop' == state.attributes['effect'] + assert 170 == state.attributes['white_value'] # Test a color command common.turn_on(self.hass, 'light.test', brightness=50, hs_color=(125, 100)) self.hass.block_till_done() - self.assertEqual('test_light_rgb/set', - self.mock_publish.async_publish.mock_calls[0][1][0]) - self.assertEqual(2, - self.mock_publish.async_publish.mock_calls[0][1][2]) - self.assertEqual(False, - self.mock_publish.async_publish.mock_calls[0][1][3]) + assert 'test_light_rgb/set' == \ + self.mock_publish.async_publish.mock_calls[0][1][0] + assert 2 == \ + self.mock_publish.async_publish.mock_calls[0][1][2] + assert self.mock_publish.async_publish.mock_calls[0][1][3] is False # Get the sent message message_json = json.loads( self.mock_publish.async_publish.mock_calls[1][1][1]) - self.assertEqual(50, message_json["brightness"]) - self.assertEqual({ + assert 50 == message_json["brightness"] + assert { 'r': 0, 'g': 255, 'b': 21, - }, message_json["color"]) - self.assertEqual("ON", message_json["state"]) + } == message_json["color"] + assert "ON" == message_json["state"] state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(50, state.attributes['brightness']) - self.assertEqual((125, 100), state.attributes['hs_color']) + assert STATE_ON == state.state + assert 50 == state.attributes['brightness'] + assert (125, 100) == state.attributes['hs_color'] def test_sending_hs_color(self): """Test light.turn_on with hs color sends hs color parameters.""" @@ -406,11 +404,11 @@ class TestLightMQTTJSON(unittest.TestCase): message_json = json.loads( self.mock_publish.async_publish.mock_calls[0][1][1]) - self.assertEqual("ON", message_json["state"]) - self.assertEqual({ + assert "ON" == message_json["state"] + assert { 'h': 180.0, 's': 50.0, - }, message_json["color"]) + } == message_json["color"] def test_flash_short_and_long(self): """Test for flash length being sent when included.""" @@ -427,39 +425,37 @@ class TestLightMQTTJSON(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertEqual(40, state.attributes.get(ATTR_SUPPORTED_FEATURES)) + assert STATE_OFF == state.state + assert 40 == state.attributes.get(ATTR_SUPPORTED_FEATURES) common.turn_on(self.hass, 'light.test', flash="short") self.hass.block_till_done() - self.assertEqual('test_light_rgb/set', - self.mock_publish.async_publish.mock_calls[0][1][0]) - self.assertEqual(0, - self.mock_publish.async_publish.mock_calls[0][1][2]) - self.assertEqual(False, - self.mock_publish.async_publish.mock_calls[0][1][3]) + assert 'test_light_rgb/set' == \ + self.mock_publish.async_publish.mock_calls[0][1][0] + assert 0 == \ + self.mock_publish.async_publish.mock_calls[0][1][2] + assert self.mock_publish.async_publish.mock_calls[0][1][3] is False # Get the sent message message_json = json.loads( self.mock_publish.async_publish.mock_calls[0][1][1]) - self.assertEqual(5, message_json["flash"]) - self.assertEqual("ON", message_json["state"]) + assert 5 == message_json["flash"] + assert "ON" == message_json["state"] self.mock_publish.async_publish.reset_mock() common.turn_on(self.hass, 'light.test', flash="long") self.hass.block_till_done() - self.assertEqual('test_light_rgb/set', - self.mock_publish.async_publish.mock_calls[0][1][0]) - self.assertEqual(0, - self.mock_publish.async_publish.mock_calls[0][1][2]) - self.assertEqual(False, - self.mock_publish.async_publish.mock_calls[0][1][3]) + assert 'test_light_rgb/set' == \ + self.mock_publish.async_publish.mock_calls[0][1][0] + assert 0 == \ + self.mock_publish.async_publish.mock_calls[0][1][2] + assert self.mock_publish.async_publish.mock_calls[0][1][3] is False # Get the sent message message_json = json.loads( self.mock_publish.async_publish.mock_calls[0][1][1]) - self.assertEqual(15, message_json["flash"]) - self.assertEqual("ON", message_json["state"]) + assert 15 == message_json["flash"] + assert "ON" == message_json["state"] def test_transition(self): """Test for transition time being sent when included.""" @@ -474,39 +470,37 @@ class TestLightMQTTJSON(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertEqual(40, state.attributes.get(ATTR_SUPPORTED_FEATURES)) + assert STATE_OFF == state.state + assert 40 == state.attributes.get(ATTR_SUPPORTED_FEATURES) common.turn_on(self.hass, 'light.test', transition=10) self.hass.block_till_done() - self.assertEqual('test_light_rgb/set', - self.mock_publish.async_publish.mock_calls[0][1][0]) - self.assertEqual(0, - self.mock_publish.async_publish.mock_calls[0][1][2]) - self.assertEqual(False, - self.mock_publish.async_publish.mock_calls[0][1][3]) + assert 'test_light_rgb/set' == \ + self.mock_publish.async_publish.mock_calls[0][1][0] + assert 0 == \ + self.mock_publish.async_publish.mock_calls[0][1][2] + assert self.mock_publish.async_publish.mock_calls[0][1][3] is False # Get the sent message message_json = json.loads( self.mock_publish.async_publish.mock_calls[0][1][1]) - self.assertEqual(10, message_json["transition"]) - self.assertEqual("ON", message_json["state"]) + assert 10 == message_json["transition"] + assert "ON" == message_json["state"] # Transition back off common.turn_off(self.hass, 'light.test', transition=10) self.hass.block_till_done() - self.assertEqual('test_light_rgb/set', - self.mock_publish.async_publish.mock_calls[1][1][0]) - self.assertEqual(0, - self.mock_publish.async_publish.mock_calls[1][1][2]) - self.assertEqual(False, - self.mock_publish.async_publish.mock_calls[1][1][3]) + assert 'test_light_rgb/set' == \ + self.mock_publish.async_publish.mock_calls[1][1][0] + assert 0 == \ + self.mock_publish.async_publish.mock_calls[1][1][2] + assert self.mock_publish.async_publish.mock_calls[1][1][3] is False # Get the sent message message_json = json.loads( self.mock_publish.async_publish.mock_calls[1][1][1]) - self.assertEqual(10, message_json["transition"]) - self.assertEqual("OFF", message_json["state"]) + assert 10 == message_json["transition"] + assert "OFF" == message_json["state"] def test_brightness_scale(self): """Test for brightness scaling.""" @@ -522,9 +516,9 @@ class TestLightMQTTJSON(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('brightness')) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert state.attributes.get('brightness') is None + assert not state.attributes.get(ATTR_ASSUMED_STATE) # Turn on the light fire_mqtt_message(self.hass, 'test_light_bright_scale', @@ -532,8 +526,8 @@ class TestLightMQTTJSON(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(255, state.attributes.get('brightness')) + assert STATE_ON == state.state + assert 255 == state.attributes.get('brightness') # Turn on the light with brightness fire_mqtt_message(self.hass, 'test_light_bright_scale', @@ -542,8 +536,8 @@ class TestLightMQTTJSON(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(255, state.attributes.get('brightness')) + assert STATE_ON == state.state + assert 255 == state.attributes.get('brightness') def test_invalid_color_brightness_and_white_values(self): """Test that invalid color/brightness/white values are ignored.""" @@ -561,12 +555,12 @@ class TestLightMQTTJSON(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertEqual(185, state.attributes.get(ATTR_SUPPORTED_FEATURES)) - self.assertIsNone(state.attributes.get('rgb_color')) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('white_value')) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert 185 == state.attributes.get(ATTR_SUPPORTED_FEATURES) + assert state.attributes.get('rgb_color') is None + assert state.attributes.get('brightness') is None + assert state.attributes.get('white_value') is None + assert not state.attributes.get(ATTR_ASSUMED_STATE) # Turn on the light fire_mqtt_message(self.hass, 'test_light_rgb', @@ -577,10 +571,10 @@ class TestLightMQTTJSON(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual((255, 255, 255), state.attributes.get('rgb_color')) - self.assertEqual(255, state.attributes.get('brightness')) - self.assertEqual(255, state.attributes.get('white_value')) + assert STATE_ON == state.state + assert (255, 255, 255) == state.attributes.get('rgb_color') + assert 255 == state.attributes.get('brightness') + assert 255 == state.attributes.get('white_value') # Bad color values fire_mqtt_message(self.hass, 'test_light_rgb', @@ -590,8 +584,8 @@ class TestLightMQTTJSON(unittest.TestCase): # Color should not have changed state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual((255, 255, 255), state.attributes.get('rgb_color')) + assert STATE_ON == state.state + assert (255, 255, 255) == state.attributes.get('rgb_color') # Bad brightness values fire_mqtt_message(self.hass, 'test_light_rgb', @@ -601,8 +595,8 @@ class TestLightMQTTJSON(unittest.TestCase): # Brightness should not have changed state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(255, state.attributes.get('brightness')) + assert STATE_ON == state.state + assert 255 == state.attributes.get('brightness') # Bad white value fire_mqtt_message(self.hass, 'test_light_rgb', @@ -612,12 +606,12 @@ class TestLightMQTTJSON(unittest.TestCase): # White value should not have changed state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(255, state.attributes.get('white_value')) + assert STATE_ON == state.state + assert 255 == state.attributes.get('white_value') def test_default_availability_payload(self): """Test availability by default payload with defined topic.""" - self.assertTrue(setup_component(self.hass, light.DOMAIN, { + assert setup_component(self.hass, light.DOMAIN, { light.DOMAIN: { 'platform': 'mqtt_json', 'name': 'test', @@ -625,26 +619,26 @@ class TestLightMQTTJSON(unittest.TestCase): 'command_topic': 'test_light_rgb/set', 'availability_topic': 'availability-topic' } - })) + }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'online') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'offline') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def test_custom_availability_payload(self): """Test availability by custom payload with defined topic.""" - self.assertTrue(setup_component(self.hass, light.DOMAIN, { + assert setup_component(self.hass, light.DOMAIN, { light.DOMAIN: { 'platform': 'mqtt_json', 'name': 'test', @@ -654,22 +648,22 @@ class TestLightMQTTJSON(unittest.TestCase): 'payload_available': 'good', 'payload_not_available': 'nogood' } - })) + }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'good') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'nogood') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state async def test_discovery_removal(hass, mqtt_mock, caplog): diff --git a/tests/components/light/test_mqtt_template.py b/tests/components/light/test_mqtt_template.py index 731e7cd4e..2d702fcb2 100644 --- a/tests/components/light/test_mqtt_template.py +++ b/tests/components/light/test_mqtt_template.py @@ -62,7 +62,7 @@ class TestLightMQTTTemplate(unittest.TestCase): 'name': 'test', } }) - self.assertIsNone(self.hass.states.get('light.test')) + assert self.hass.states.get('light.test') is None def test_state_change_via_topic(self): """Test state change via topic.""" @@ -86,22 +86,22 @@ class TestLightMQTTTemplate(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('rgb_color')) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('color_temp')) - self.assertIsNone(state.attributes.get('white_value')) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert state.attributes.get('rgb_color') is None + assert state.attributes.get('brightness') is None + assert state.attributes.get('color_temp') is None + assert state.attributes.get('white_value') is None + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'test_light_rgb', 'on') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('rgb_color')) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('color_temp')) - self.assertIsNone(state.attributes.get('white_value')) + assert STATE_ON == state.state + assert state.attributes.get('rgb_color') is None + assert state.attributes.get('brightness') is None + assert state.attributes.get('color_temp') is None + assert state.attributes.get('white_value') is None def test_state_brightness_color_effect_temp_white_change_via_topic(self): """Test state, bri, color, effect, color temp, white val change.""" @@ -137,13 +137,13 @@ class TestLightMQTTTemplate(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('rgb_color')) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('effect')) - self.assertIsNone(state.attributes.get('color_temp')) - self.assertIsNone(state.attributes.get('white_value')) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert state.attributes.get('rgb_color') is None + assert state.attributes.get('brightness') is None + assert state.attributes.get('effect') is None + assert state.attributes.get('color_temp') is None + assert state.attributes.get('white_value') is None + assert not state.attributes.get(ATTR_ASSUMED_STATE) # turn on the light, full white fire_mqtt_message(self.hass, 'test_light_rgb', @@ -151,19 +151,19 @@ class TestLightMQTTTemplate(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual((255, 128, 63), state.attributes.get('rgb_color')) - self.assertEqual(255, state.attributes.get('brightness')) - self.assertEqual(145, state.attributes.get('color_temp')) - self.assertEqual(123, state.attributes.get('white_value')) - self.assertIsNone(state.attributes.get('effect')) + assert STATE_ON == state.state + assert (255, 128, 63) == state.attributes.get('rgb_color') + assert 255 == state.attributes.get('brightness') + assert 145 == state.attributes.get('color_temp') + assert 123 == state.attributes.get('white_value') + assert state.attributes.get('effect') is None # turn the light off fire_mqtt_message(self.hass, 'test_light_rgb', 'off') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state # lower the brightness fire_mqtt_message(self.hass, 'test_light_rgb', 'on,100') @@ -171,7 +171,7 @@ class TestLightMQTTTemplate(unittest.TestCase): light_state = self.hass.states.get('light.test') self.hass.block_till_done() - self.assertEqual(100, light_state.attributes['brightness']) + assert 100 == light_state.attributes['brightness'] # change the color temp fire_mqtt_message(self.hass, 'test_light_rgb', 'on,,195') @@ -179,15 +179,15 @@ class TestLightMQTTTemplate(unittest.TestCase): light_state = self.hass.states.get('light.test') self.hass.block_till_done() - self.assertEqual(195, light_state.attributes['color_temp']) + assert 195 == light_state.attributes['color_temp'] # change the color fire_mqtt_message(self.hass, 'test_light_rgb', 'on,,,,41-42-43') self.hass.block_till_done() light_state = self.hass.states.get('light.test') - self.assertEqual((243, 249, 255), - light_state.attributes.get('rgb_color')) + assert (243, 249, 255) == \ + light_state.attributes.get('rgb_color') # change the white value fire_mqtt_message(self.hass, 'test_light_rgb', 'on,,,134') @@ -195,7 +195,7 @@ class TestLightMQTTTemplate(unittest.TestCase): light_state = self.hass.states.get('light.test') self.hass.block_till_done() - self.assertEqual(134, light_state.attributes['white_value']) + assert 134 == light_state.attributes['white_value'] # change the effect fire_mqtt_message(self.hass, 'test_light_rgb', @@ -203,7 +203,7 @@ class TestLightMQTTTemplate(unittest.TestCase): self.hass.block_till_done() light_state = self.hass.states.get('light.test') - self.assertEqual('rainbow', light_state.attributes.get('effect')) + assert 'rainbow' == light_state.attributes.get('effect') def test_optimistic(self): """Test optimistic mode.""" @@ -237,13 +237,13 @@ class TestLightMQTTTemplate(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(95, state.attributes.get('brightness')) - self.assertEqual((100, 100), state.attributes.get('hs_color')) - self.assertEqual('random', state.attributes.get('effect')) - self.assertEqual(100, state.attributes.get('color_temp')) - self.assertEqual(50, state.attributes.get('white_value')) - self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_ON == state.state + assert 95 == state.attributes.get('brightness') + assert (100, 100) == state.attributes.get('hs_color') + assert 'random' == state.attributes.get('effect') + assert 100 == state.attributes.get('color_temp') + assert 50 == state.attributes.get('white_value') + assert state.attributes.get(ATTR_ASSUMED_STATE) # turn on the light common.turn_on(self.hass, 'light.test') @@ -253,7 +253,7 @@ class TestLightMQTTTemplate(unittest.TestCase): 'test_light_rgb/set', 'on,,,,--', 2, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state # turn the light off common.turn_off(self.hass, 'light.test') @@ -263,7 +263,7 @@ class TestLightMQTTTemplate(unittest.TestCase): 'test_light_rgb/set', 'off', 2, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state # turn on the light with brightness, color common.turn_on(self.hass, 'light.test', brightness=50, @@ -284,11 +284,11 @@ class TestLightMQTTTemplate(unittest.TestCase): # check the state state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual((255, 255, 255), state.attributes['rgb_color']) - self.assertEqual(50, state.attributes['brightness']) - self.assertEqual(200, state.attributes['color_temp']) - self.assertEqual(139, state.attributes['white_value']) + assert STATE_ON == state.state + assert (255, 255, 255) == state.attributes['rgb_color'] + assert 50 == state.attributes['brightness'] + assert 200 == state.attributes['color_temp'] + assert 139 == state.attributes['white_value'] def test_flash(self): """Test flash.""" @@ -305,7 +305,7 @@ class TestLightMQTTTemplate(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state # short flash common.turn_on(self.hass, 'light.test', flash='short') @@ -336,7 +336,7 @@ class TestLightMQTTTemplate(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state # transition on common.turn_on(self.hass, 'light.test', transition=10) @@ -386,13 +386,13 @@ class TestLightMQTTTemplate(unittest.TestCase): }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_OFF, state.state) - self.assertIsNone(state.attributes.get('rgb_color')) - self.assertIsNone(state.attributes.get('brightness')) - self.assertIsNone(state.attributes.get('color_temp')) - self.assertIsNone(state.attributes.get('effect')) - self.assertIsNone(state.attributes.get('white_value')) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert state.attributes.get('rgb_color') is None + assert state.attributes.get('brightness') is None + assert state.attributes.get('color_temp') is None + assert state.attributes.get('effect') is None + assert state.attributes.get('white_value') is None + assert not state.attributes.get(ATTR_ASSUMED_STATE) # turn on the light, full white fire_mqtt_message(self.hass, 'test_light_rgb', @@ -400,12 +400,12 @@ class TestLightMQTTTemplate(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) - self.assertEqual(255, state.attributes.get('brightness')) - self.assertEqual(215, state.attributes.get('color_temp')) - self.assertEqual((255, 255, 255), state.attributes.get('rgb_color')) - self.assertEqual(222, state.attributes.get('white_value')) - self.assertEqual('rainbow', state.attributes.get('effect')) + assert STATE_ON == state.state + assert 255 == state.attributes.get('brightness') + assert 215 == state.attributes.get('color_temp') + assert (255, 255, 255) == state.attributes.get('rgb_color') + assert 222 == state.attributes.get('white_value') + assert 'rainbow' == state.attributes.get('effect') # bad state value fire_mqtt_message(self.hass, 'test_light_rgb', 'offf') @@ -413,7 +413,7 @@ class TestLightMQTTTemplate(unittest.TestCase): # state should not have changed state = self.hass.states.get('light.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state # bad brightness values fire_mqtt_message(self.hass, 'test_light_rgb', 'on,off,255-255-255') @@ -421,7 +421,7 @@ class TestLightMQTTTemplate(unittest.TestCase): # brightness should not have changed state = self.hass.states.get('light.test') - self.assertEqual(255, state.attributes.get('brightness')) + assert 255 == state.attributes.get('brightness') # bad color temp values fire_mqtt_message(self.hass, 'test_light_rgb', 'on,,off,255-255-255') @@ -429,7 +429,7 @@ class TestLightMQTTTemplate(unittest.TestCase): # color temp should not have changed state = self.hass.states.get('light.test') - self.assertEqual(215, state.attributes.get('color_temp')) + assert 215 == state.attributes.get('color_temp') # bad color values fire_mqtt_message(self.hass, 'test_light_rgb', 'on,255,a-b-c') @@ -437,7 +437,7 @@ class TestLightMQTTTemplate(unittest.TestCase): # color should not have changed state = self.hass.states.get('light.test') - self.assertEqual((255, 255, 255), state.attributes.get('rgb_color')) + assert (255, 255, 255) == state.attributes.get('rgb_color') # bad white value values fire_mqtt_message(self.hass, 'test_light_rgb', 'on,,,off,255-255-255') @@ -445,7 +445,7 @@ class TestLightMQTTTemplate(unittest.TestCase): # white value should not have changed state = self.hass.states.get('light.test') - self.assertEqual(222, state.attributes.get('white_value')) + assert 222 == state.attributes.get('white_value') # bad effect value fire_mqtt_message(self.hass, 'test_light_rgb', 'on,255,a-b-c,white') @@ -453,11 +453,11 @@ class TestLightMQTTTemplate(unittest.TestCase): # effect should not have changed state = self.hass.states.get('light.test') - self.assertEqual('rainbow', state.attributes.get('effect')) + assert 'rainbow' == state.attributes.get('effect') def test_default_availability_payload(self): """Test availability by default payload with defined topic.""" - self.assertTrue(setup_component(self.hass, light.DOMAIN, { + assert setup_component(self.hass, light.DOMAIN, { light.DOMAIN: { 'platform': 'mqtt_template', 'name': 'test', @@ -466,26 +466,26 @@ class TestLightMQTTTemplate(unittest.TestCase): 'command_off_template': 'off,{{ transition|d }}', 'availability_topic': 'availability-topic' } - })) + }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'online') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'offline') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def test_custom_availability_payload(self): """Test availability by custom payload with defined topic.""" - self.assertTrue(setup_component(self.hass, light.DOMAIN, { + assert setup_component(self.hass, light.DOMAIN, { light.DOMAIN: { 'platform': 'mqtt_template', 'name': 'test', @@ -496,19 +496,19 @@ class TestLightMQTTTemplate(unittest.TestCase): 'payload_available': 'good', 'payload_not_available': 'nogood' } - })) + }) state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'good') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'nogood') self.hass.block_till_done() state = self.hass.states.get('light.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state diff --git a/tests/components/light/test_rfxtrx.py b/tests/components/light/test_rfxtrx.py index 8a8e94ec1..d7f9feee8 100644 --- a/tests/components/light/test_rfxtrx.py +++ b/tests/components/light/test_rfxtrx.py @@ -28,26 +28,26 @@ class TestLightRfxtrx(unittest.TestCase): def test_valid_config(self): """Test configuration.""" - self.assertTrue(setup_component(self.hass, 'light', { + assert setup_component(self.hass, 'light', { 'light': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'0b1100cd0213c7f210010f51': { 'name': 'Test', - rfxtrx_core.ATTR_FIREEVENT: True}}}})) + rfxtrx_core.ATTR_FIREEVENT: True}}}}) - self.assertTrue(setup_component(self.hass, 'light', { + assert setup_component(self.hass, 'light', { 'light': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'213c7f216': { 'name': 'Test', 'packetid': '0b1100cd0213c7f210010f51', - 'signal_repetitions': 3}}}})) + 'signal_repetitions': 3}}}}) def test_invalid_config(self): """Test configuration.""" - self.assertFalse(setup_component(self.hass, 'light', { + assert not setup_component(self.hass, 'light', { 'light': {'platform': 'rfxtrx', 'automatic_add': True, 'invalid_key': 'afda', @@ -55,182 +55,183 @@ class TestLightRfxtrx(unittest.TestCase): {'213c7f216': { 'name': 'Test', 'packetid': '0b1100cd0213c7f210010f51', - rfxtrx_core.ATTR_FIREEVENT: True}}}})) + rfxtrx_core.ATTR_FIREEVENT: True}}}}) def test_default_config(self): """Test with 0 switches.""" - self.assertTrue(setup_component(self.hass, 'light', { + assert setup_component(self.hass, 'light', { 'light': {'platform': 'rfxtrx', - 'devices': {}}})) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + 'devices': {}}}) + assert 0 == len(rfxtrx_core.RFX_DEVICES) def test_old_config(self): """Test with 1 light.""" - self.assertTrue(setup_component(self.hass, 'light', { + assert setup_component(self.hass, 'light', { 'light': {'platform': 'rfxtrx', 'devices': {'123efab1': { 'name': 'Test', - 'packetid': '0b1100cd0213c7f210010f51'}}}})) + 'packetid': '0b1100cd0213c7f210010f51'}}}}) import RFXtrx as rfxtrxmod rfxtrx_core.RFXOBJECT =\ rfxtrxmod.Core("", transport_protocol=rfxtrxmod.DummyTransport) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) entity = rfxtrx_core.RFX_DEVICES['213c7f216'] - self.assertEqual('Test', entity.name) - self.assertEqual('off', entity.state) - self.assertTrue(entity.assumed_state) - self.assertEqual(entity.signal_repetitions, 1) - self.assertFalse(entity.should_fire_event) - self.assertFalse(entity.should_poll) + assert 'Test' == entity.name + assert 'off' == entity.state + assert entity.assumed_state + assert entity.signal_repetitions == 1 + assert not entity.should_fire_event + assert not entity.should_poll - self.assertFalse(entity.is_on) + assert not entity.is_on entity.turn_on() - self.assertTrue(entity.is_on) - self.assertEqual(entity.brightness, 255) + assert entity.is_on + assert entity.brightness == 255 entity.turn_off() - self.assertFalse(entity.is_on) - self.assertEqual(entity.brightness, 0) + assert not entity.is_on + assert entity.brightness == 0 entity.turn_on(brightness=100) - self.assertTrue(entity.is_on) - self.assertEqual(entity.brightness, 100) + assert entity.is_on + assert entity.brightness == 100 entity.turn_on(brightness=10) - self.assertTrue(entity.is_on) - self.assertEqual(entity.brightness, 10) + assert entity.is_on + assert entity.brightness == 10 entity.turn_on(brightness=255) - self.assertTrue(entity.is_on) - self.assertEqual(entity.brightness, 255) + assert entity.is_on + assert entity.brightness == 255 def test_one_light(self): """Test with 1 light.""" - self.assertTrue(setup_component(self.hass, 'light', { + assert setup_component(self.hass, 'light', { 'light': {'platform': 'rfxtrx', 'devices': {'0b1100cd0213c7f210010f51': { - 'name': 'Test'}}}})) + 'name': 'Test'}}}}) import RFXtrx as rfxtrxmod rfxtrx_core.RFXOBJECT =\ rfxtrxmod.Core("", transport_protocol=rfxtrxmod.DummyTransport) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) entity = rfxtrx_core.RFX_DEVICES['213c7f216'] - self.assertEqual('Test', entity.name) - self.assertEqual('off', entity.state) - self.assertTrue(entity.assumed_state) - self.assertEqual(entity.signal_repetitions, 1) - self.assertFalse(entity.should_fire_event) - self.assertFalse(entity.should_poll) + assert 'Test' == entity.name + assert 'off' == entity.state + assert entity.assumed_state + assert entity.signal_repetitions == 1 + assert not entity.should_fire_event + assert not entity.should_poll - self.assertFalse(entity.is_on) + assert not entity.is_on entity.turn_on() - self.assertTrue(entity.is_on) - self.assertEqual(entity.brightness, 255) + assert entity.is_on + assert entity.brightness == 255 entity.turn_off() - self.assertFalse(entity.is_on) - self.assertEqual(entity.brightness, 0) + assert not entity.is_on + assert entity.brightness == 0 entity.turn_on(brightness=100) - self.assertTrue(entity.is_on) - self.assertEqual(entity.brightness, 100) + assert entity.is_on + assert entity.brightness == 100 entity.turn_on(brightness=10) - self.assertTrue(entity.is_on) - self.assertEqual(entity.brightness, 10) + assert entity.is_on + assert entity.brightness == 10 entity.turn_on(brightness=255) - self.assertTrue(entity.is_on) - self.assertEqual(entity.brightness, 255) + assert entity.is_on + assert entity.brightness == 255 entity.turn_off() entity_id = rfxtrx_core.RFX_DEVICES['213c7f216'].entity_id entity_hass = self.hass.states.get(entity_id) - self.assertEqual('Test', entity_hass.name) - self.assertEqual('off', entity_hass.state) + assert 'Test' == entity_hass.name + assert 'off' == entity_hass.state entity.turn_on() entity_hass = self.hass.states.get(entity_id) - self.assertEqual('on', entity_hass.state) + assert 'on' == entity_hass.state entity.turn_off() entity_hass = self.hass.states.get(entity_id) - self.assertEqual('off', entity_hass.state) + assert 'off' == entity_hass.state entity.turn_on(brightness=100) entity_hass = self.hass.states.get(entity_id) - self.assertEqual('on', entity_hass.state) + assert 'on' == entity_hass.state entity.turn_on(brightness=10) entity_hass = self.hass.states.get(entity_id) - self.assertEqual('on', entity_hass.state) + assert 'on' == entity_hass.state entity.turn_on(brightness=255) entity_hass = self.hass.states.get(entity_id) - self.assertEqual('on', entity_hass.state) + assert 'on' == entity_hass.state def test_several_lights(self): """Test with 3 lights.""" - self.assertTrue(setup_component(self.hass, 'light', { - 'light': {'platform': 'rfxtrx', - 'signal_repetitions': 3, - 'devices': - {'0b1100cd0213c7f230010f71': { - 'name': 'Test'}, - '0b1100100118cdea02010f70': { - 'name': 'Bath'}, - '0b1100101118cdea02010f70': { - 'name': 'Living'}}}})) + assert setup_component(self.hass, 'light', { + 'light': { + 'platform': 'rfxtrx', + 'signal_repetitions': 3, + 'devices': { + '0b1100cd0213c7f230010f71': { + 'name': 'Test'}, + '0b1100100118cdea02010f70': { + 'name': 'Bath'}, + '0b1100101118cdea02010f70': { + 'name': 'Living'}}}}) - self.assertEqual(3, len(rfxtrx_core.RFX_DEVICES)) + assert 3 == len(rfxtrx_core.RFX_DEVICES) device_num = 0 for id in rfxtrx_core.RFX_DEVICES: entity = rfxtrx_core.RFX_DEVICES[id] - self.assertEqual(entity.signal_repetitions, 3) + assert entity.signal_repetitions == 3 if entity.name == 'Living': device_num = device_num + 1 - self.assertEqual('off', entity.state) - self.assertEqual('', entity.__str__()) + assert 'off' == entity.state + assert '' == entity.__str__() elif entity.name == 'Bath': device_num = device_num + 1 - self.assertEqual('off', entity.state) - self.assertEqual('', entity.__str__()) + assert 'off' == entity.state + assert '' == entity.__str__() elif entity.name == 'Test': device_num = device_num + 1 - self.assertEqual('off', entity.state) - self.assertEqual('', entity.__str__()) + assert 'off' == entity.state + assert '' == entity.__str__() - self.assertEqual(3, device_num) + assert 3 == device_num def test_discover_light(self): """Test with discovery of lights.""" - self.assertTrue(setup_component(self.hass, 'light', { + assert setup_component(self.hass, 'light', { 'light': {'platform': 'rfxtrx', 'automatic_add': True, - 'devices': {}}})) + 'devices': {}}}) event = rfxtrx_core.get_rfx_object('0b11009e00e6116202020070') event.data = bytearray(b'\x0b\x11\x00\x9e\x00\xe6\x11b\x02\x02\x00p') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) entity = rfxtrx_core.RFX_DEVICES['0e611622'] - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) - self.assertEqual('', - entity.__str__()) + assert 1 == len(rfxtrx_core.RFX_DEVICES) + assert '' == \ + entity.__str__() event = rfxtrx_core.get_rfx_object('0b11009e00e6116201010070') event.data = bytearray(b'\x0b\x11\x00\x9e\x00\xe6\x11b\x01\x01\x00p') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) event = rfxtrx_core.get_rfx_object('0b1100120118cdea02020070') event.data = bytearray([0x0b, 0x11, 0x00, 0x12, 0x01, 0x18, @@ -238,15 +239,15 @@ class TestLightRfxtrx(unittest.TestCase): rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) entity = rfxtrx_core.RFX_DEVICES['118cdea2'] - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) - self.assertEqual('', - entity.__str__()) + assert 2 == len(rfxtrx_core.RFX_DEVICES) + assert '' == \ + entity.__str__() # trying to add a sensor event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray(b'\nR\x08^\x07\x01\x00\xb3\x1b\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) # trying to add a switch event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') @@ -254,59 +255,59 @@ class TestLightRfxtrx(unittest.TestCase): 0xcd, 0xea, 0x01, 0x01, 0x0f, 0x70]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a rollershutter event = rfxtrx_core.get_rfx_object('0a1400adf394ab020e0060') event.data = bytearray([0x0A, 0x14, 0x00, 0xAD, 0xF3, 0x94, 0xAB, 0x02, 0x0E, 0x00, 0x60]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) def test_discover_light_noautoadd(self): """Test with discover of light when auto add is False.""" - self.assertTrue(setup_component(self.hass, 'light', { + assert setup_component(self.hass, 'light', { 'light': {'platform': 'rfxtrx', 'automatic_add': False, - 'devices': {}}})) + 'devices': {}}}) event = rfxtrx_core.get_rfx_object('0b1100120118cdea02020070') event.data = bytearray([0x0b, 0x11, 0x00, 0x12, 0x01, 0x18, 0xcd, 0xea, 0x02, 0x02, 0x00, 0x70]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) event = rfxtrx_core.get_rfx_object('0b1100120118cdea02010070') event.data = bytearray([0x0b, 0x11, 0x00, 0x12, 0x01, 0x18, 0xcd, 0xea, 0x02, 0x01, 0x00, 0x70]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) event = rfxtrx_core.get_rfx_object('0b1100120118cdea02020070') event.data = bytearray([0x0b, 0x11, 0x00, 0x12, 0x01, 0x18, 0xcd, 0xea, 0x02, 0x02, 0x00, 0x70]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a sensor event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray(b'\nR\x08^\x07\x01\x00\xb3\x1b\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a switch event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') event.data = bytearray([0x0b, 0x11, 0x00, 0x10, 0x01, 0x18, 0xcd, 0xea, 0x01, 0x01, 0x0f, 0x70]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a rollershutter event = rfxtrx_core.get_rfx_object('0a1400adf394ab020e0060') event.data = bytearray([0x0A, 0x14, 0x00, 0xAD, 0xF3, 0x94, 0xAB, 0x02, 0x0E, 0x00, 0x60]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) diff --git a/tests/components/lock/test_demo.py b/tests/components/lock/test_demo.py index 255e5307f..509b34869 100644 --- a/tests/components/lock/test_demo.py +++ b/tests/components/lock/test_demo.py @@ -18,11 +18,11 @@ class TestLockDemo(unittest.TestCase): def setUp(self): # pylint: disable=invalid-name """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() - self.assertTrue(setup_component(self.hass, lock.DOMAIN, { + assert setup_component(self.hass, lock.DOMAIN, { 'lock': { 'platform': 'demo' } - })) + }) def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" @@ -30,10 +30,10 @@ class TestLockDemo(unittest.TestCase): def test_is_locked(self): """Test if lock is locked.""" - self.assertTrue(lock.is_locked(self.hass, FRONT)) + assert lock.is_locked(self.hass, FRONT) self.hass.states.is_state(FRONT, 'locked') - self.assertFalse(lock.is_locked(self.hass, KITCHEN)) + assert not lock.is_locked(self.hass, KITCHEN) self.hass.states.is_state(KITCHEN, 'unlocked') def test_locking(self): @@ -41,18 +41,18 @@ class TestLockDemo(unittest.TestCase): common.lock(self.hass, KITCHEN) self.hass.block_till_done() - self.assertTrue(lock.is_locked(self.hass, KITCHEN)) + assert lock.is_locked(self.hass, KITCHEN) def test_unlocking(self): """Test the unlocking of a lock.""" common.unlock(self.hass, FRONT) self.hass.block_till_done() - self.assertFalse(lock.is_locked(self.hass, FRONT)) + assert not lock.is_locked(self.hass, FRONT) def test_opening(self): """Test the opening of a lock.""" calls = mock_service(self.hass, lock.DOMAIN, lock.SERVICE_OPEN) common.open_lock(self.hass, OPENABLE_LOCK) self.hass.block_till_done() - self.assertEqual(1, len(calls)) + assert 1 == len(calls) diff --git a/tests/components/lock/test_mqtt.py b/tests/components/lock/test_mqtt.py index 4d2378ff9..a7bb06fc2 100644 --- a/tests/components/lock/test_mqtt.py +++ b/tests/components/lock/test_mqtt.py @@ -39,20 +39,20 @@ class TestLockMQTT(unittest.TestCase): }) state = self.hass.states.get('lock.test') - self.assertEqual(STATE_UNLOCKED, state.state) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_UNLOCKED == state.state + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'state-topic', 'LOCK') self.hass.block_till_done() state = self.hass.states.get('lock.test') - self.assertEqual(STATE_LOCKED, state.state) + assert STATE_LOCKED == state.state fire_mqtt_message(self.hass, 'state-topic', 'UNLOCK') self.hass.block_till_done() state = self.hass.states.get('lock.test') - self.assertEqual(STATE_UNLOCKED, state.state) + assert STATE_UNLOCKED == state.state def test_sending_mqtt_commands_and_optimistic(self): """Test the sending MQTT commands in optimistic mode.""" @@ -68,8 +68,8 @@ class TestLockMQTT(unittest.TestCase): }) state = self.hass.states.get('lock.test') - self.assertEqual(STATE_UNLOCKED, state.state) - self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_UNLOCKED == state.state + assert state.attributes.get(ATTR_ASSUMED_STATE) common.lock(self.hass, 'lock.test') self.hass.block_till_done() @@ -78,7 +78,7 @@ class TestLockMQTT(unittest.TestCase): 'command-topic', 'LOCK', 2, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get('lock.test') - self.assertEqual(STATE_LOCKED, state.state) + assert STATE_LOCKED == state.state common.unlock(self.hass, 'lock.test') self.hass.block_till_done() @@ -86,7 +86,7 @@ class TestLockMQTT(unittest.TestCase): self.mock_publish.async_publish.assert_called_once_with( 'command-topic', 'UNLOCK', 2, False) state = self.hass.states.get('lock.test') - self.assertEqual(STATE_UNLOCKED, state.state) + assert STATE_UNLOCKED == state.state def test_controlling_state_via_topic_and_json_message(self): """Test the controlling state via topic and JSON message.""" @@ -103,23 +103,23 @@ class TestLockMQTT(unittest.TestCase): }) state = self.hass.states.get('lock.test') - self.assertEqual(STATE_UNLOCKED, state.state) + assert STATE_UNLOCKED == state.state fire_mqtt_message(self.hass, 'state-topic', '{"val":"LOCK"}') self.hass.block_till_done() state = self.hass.states.get('lock.test') - self.assertEqual(STATE_LOCKED, state.state) + assert STATE_LOCKED == state.state fire_mqtt_message(self.hass, 'state-topic', '{"val":"UNLOCK"}') self.hass.block_till_done() state = self.hass.states.get('lock.test') - self.assertEqual(STATE_UNLOCKED, state.state) + assert STATE_UNLOCKED == state.state def test_default_availability_payload(self): """Test availability by default payload with defined topic.""" - self.assertTrue(setup_component(self.hass, lock.DOMAIN, { + assert setup_component(self.hass, lock.DOMAIN, { lock.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -129,26 +129,26 @@ class TestLockMQTT(unittest.TestCase): 'payload_unlock': 'UNLOCK', 'availability_topic': 'availability-topic' } - })) + }) state = self.hass.states.get('lock.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'online') self.hass.block_till_done() state = self.hass.states.get('lock.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'offline') self.hass.block_till_done() state = self.hass.states.get('lock.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def test_custom_availability_payload(self): """Test availability by custom payload with defined topic.""" - self.assertTrue(setup_component(self.hass, lock.DOMAIN, { + assert setup_component(self.hass, lock.DOMAIN, { lock.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -160,22 +160,22 @@ class TestLockMQTT(unittest.TestCase): 'payload_available': 'good', 'payload_not_available': 'nogood' } - })) + }) state = self.hass.states.get('lock.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'good') self.hass.block_till_done() state = self.hass.states.get('lock.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'nogood') self.hass.block_till_done() state = self.hass.states.get('lock.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state async def test_discovery_removal_lock(hass, mqtt_mock, caplog): diff --git a/tests/components/lovelace/test_init.py b/tests/components/lovelace/test_init.py index 1ce0f9ff6..d9465d7a7 100644 --- a/tests/components/lovelace/test_init.py +++ b/tests/components/lovelace/test_init.py @@ -11,6 +11,7 @@ from homeassistant.components.websocket_api.const import TYPE_RESULT from homeassistant.components.lovelace import (load_yaml, save_yaml, load_config, UnsupportedYamlError) +import pytest TEST_YAML_A = """\ title: My Awesome Home @@ -138,7 +139,7 @@ class TestYAML(unittest.TestCase): fname = self._path_for("test1") save_yaml(fname, self.yaml.load(TEST_YAML_A)) data = load_yaml(fname) - self.assertEqual(data, self.yaml.load(TEST_YAML_A)) + assert data == self.yaml.load(TEST_YAML_A) def test_overwrite_and_reload(self): """Test that we can overwrite an existing file and read back.""" @@ -146,14 +147,14 @@ class TestYAML(unittest.TestCase): save_yaml(fname, self.yaml.load(TEST_YAML_A)) save_yaml(fname, self.yaml.load(TEST_YAML_B)) data = load_yaml(fname) - self.assertEqual(data, self.yaml.load(TEST_YAML_B)) + assert data == self.yaml.load(TEST_YAML_B) def test_load_bad_data(self): """Test error from trying to load unserialisable data.""" fname = self._path_for("test5") with open(fname, "w") as fh: fh.write(TEST_BAD_YAML) - with self.assertRaises(HomeAssistantError): + with pytest.raises(HomeAssistantError): load_yaml(fname) def test_add_id(self): @@ -172,7 +173,7 @@ class TestYAML(unittest.TestCase): with patch('homeassistant.components.lovelace.load_yaml', return_value=self.yaml.load(TEST_YAML_B)): data = load_config(fname) - self.assertEqual(data, self.yaml.load(TEST_YAML_B)) + assert data == self.yaml.load(TEST_YAML_B) async def test_deprecated_lovelace_ui(hass, hass_ws_client): diff --git a/tests/components/media_player/test_async_helpers.py b/tests/components/media_player/test_async_helpers.py index 5908ea02a..1c4a2fa84 100644 --- a/tests/components/media_player/test_async_helpers.py +++ b/tests/components/media_player/test_async_helpers.py @@ -133,43 +133,43 @@ class TestAsyncMediaPlayer(unittest.TestCase): def test_volume_up(self): """Test the volume_up helper function.""" - self.assertEqual(self.player.volume_level, 0) + assert self.player.volume_level == 0 run_coroutine_threadsafe( self.player.async_set_volume_level(0.5), self.hass.loop).result() - self.assertEqual(self.player.volume_level, 0.5) + assert self.player.volume_level == 0.5 run_coroutine_threadsafe( self.player.async_volume_up(), self.hass.loop).result() - self.assertEqual(self.player.volume_level, 0.6) + assert self.player.volume_level == 0.6 def test_volume_down(self): """Test the volume_down helper function.""" - self.assertEqual(self.player.volume_level, 0) + assert self.player.volume_level == 0 run_coroutine_threadsafe( self.player.async_set_volume_level(0.5), self.hass.loop).result() - self.assertEqual(self.player.volume_level, 0.5) + assert self.player.volume_level == 0.5 run_coroutine_threadsafe( self.player.async_volume_down(), self.hass.loop).result() - self.assertEqual(self.player.volume_level, 0.4) + assert self.player.volume_level == 0.4 def test_media_play_pause(self): """Test the media_play_pause helper function.""" - self.assertEqual(self.player.state, STATE_OFF) + assert self.player.state == STATE_OFF run_coroutine_threadsafe( self.player.async_media_play_pause(), self.hass.loop).result() - self.assertEqual(self.player.state, STATE_PLAYING) + assert self.player.state == STATE_PLAYING run_coroutine_threadsafe( self.player.async_media_play_pause(), self.hass.loop).result() - self.assertEqual(self.player.state, STATE_PAUSED) + assert self.player.state == STATE_PAUSED def test_toggle(self): """Test the toggle helper function.""" - self.assertEqual(self.player.state, STATE_OFF) + assert self.player.state == STATE_OFF run_coroutine_threadsafe( self.player.async_toggle(), self.hass.loop).result() - self.assertEqual(self.player.state, STATE_ON) + assert self.player.state == STATE_ON run_coroutine_threadsafe( self.player.async_toggle(), self.hass.loop).result() - self.assertEqual(self.player.state, STATE_OFF) + assert self.player.state == STATE_OFF class TestSyncMediaPlayer(unittest.TestCase): @@ -186,38 +186,38 @@ class TestSyncMediaPlayer(unittest.TestCase): def test_volume_up(self): """Test the volume_up helper function.""" - self.assertEqual(self.player.volume_level, 0) + assert self.player.volume_level == 0 self.player.set_volume_level(0.5) - self.assertEqual(self.player.volume_level, 0.5) + assert self.player.volume_level == 0.5 run_coroutine_threadsafe( self.player.async_volume_up(), self.hass.loop).result() - self.assertEqual(self.player.volume_level, 0.7) + assert self.player.volume_level == 0.7 def test_volume_down(self): """Test the volume_down helper function.""" - self.assertEqual(self.player.volume_level, 0) + assert self.player.volume_level == 0 self.player.set_volume_level(0.5) - self.assertEqual(self.player.volume_level, 0.5) + assert self.player.volume_level == 0.5 run_coroutine_threadsafe( self.player.async_volume_down(), self.hass.loop).result() - self.assertEqual(self.player.volume_level, 0.3) + assert self.player.volume_level == 0.3 def test_media_play_pause(self): """Test the media_play_pause helper function.""" - self.assertEqual(self.player.state, STATE_OFF) + assert self.player.state == STATE_OFF run_coroutine_threadsafe( self.player.async_media_play_pause(), self.hass.loop).result() - self.assertEqual(self.player.state, STATE_PLAYING) + assert self.player.state == STATE_PLAYING run_coroutine_threadsafe( self.player.async_media_play_pause(), self.hass.loop).result() - self.assertEqual(self.player.state, STATE_PAUSED) + assert self.player.state == STATE_PAUSED def test_toggle(self): """Test the toggle helper function.""" - self.assertEqual(self.player.state, STATE_OFF) + assert self.player.state == STATE_OFF run_coroutine_threadsafe( self.player.async_toggle(), self.hass.loop).result() - self.assertEqual(self.player.state, STATE_ON) + assert self.player.state == STATE_ON run_coroutine_threadsafe( self.player.async_toggle(), self.hass.loop).result() - self.assertEqual(self.player.state, STATE_OFF) + assert self.player.state == STATE_OFF diff --git a/tests/components/media_player/test_blackbird.py b/tests/components/media_player/test_blackbird.py index 550bfe88a..38a63f294 100644 --- a/tests/components/media_player/test_blackbird.py +++ b/tests/components/media_player/test_blackbird.py @@ -11,6 +11,7 @@ from homeassistant.const import STATE_ON, STATE_OFF import tests.common from homeassistant.components.media_player.blackbird import ( DATA_BLACKBIRD, PLATFORM_SCHEMA, SERVICE_SETALLZONES, setup_platform) +import pytest class AttrDict(dict): @@ -157,7 +158,7 @@ class TestBlackbirdSchema(unittest.TestCase): }, ) for value in schemas: - with self.assertRaises(vol.MultipleInvalid): + with pytest.raises(vol.MultipleInvalid): PLATFORM_SCHEMA(value) @@ -192,18 +193,17 @@ class TestBlackbirdMediaPlayer(unittest.TestCase): def test_setup_platform(self, *args): """Test setting up platform.""" # One service must be registered - self.assertTrue(self.hass.services.has_service(DOMAIN, - SERVICE_SETALLZONES)) - self.assertEqual(len(self.hass.data[DATA_BLACKBIRD]), 1) - self.assertEqual(self.hass.data[DATA_BLACKBIRD]['/dev/ttyUSB0-3'].name, - 'Zone name') + assert self.hass.services.has_service(DOMAIN, SERVICE_SETALLZONES) + assert len(self.hass.data[DATA_BLACKBIRD]) == 1 + assert self.hass.data[DATA_BLACKBIRD]['/dev/ttyUSB0-3'].name == \ + 'Zone name' def test_setallzones_service_call_with_entity_id(self): """Test set all zone source service call with entity id.""" self.media_player.update() - self.assertEqual('Zone name', self.media_player.name) - self.assertEqual(STATE_ON, self.media_player.state) - self.assertEqual('one', self.media_player.source) + assert 'Zone name' == self.media_player.name + assert STATE_ON == self.media_player.state + assert 'one' == self.media_player.source # Call set all zones service self.hass.services.call(DOMAIN, SERVICE_SETALLZONES, @@ -212,110 +212,110 @@ class TestBlackbirdMediaPlayer(unittest.TestCase): blocking=True) # Check that source was changed - self.assertEqual(3, self.blackbird.zones[3].av) + assert 3 == self.blackbird.zones[3].av self.media_player.update() - self.assertEqual('three', self.media_player.source) + assert 'three' == self.media_player.source def test_setallzones_service_call_without_entity_id(self): """Test set all zone source service call without entity id.""" self.media_player.update() - self.assertEqual('Zone name', self.media_player.name) - self.assertEqual(STATE_ON, self.media_player.state) - self.assertEqual('one', self.media_player.source) + assert 'Zone name' == self.media_player.name + assert STATE_ON == self.media_player.state + assert 'one' == self.media_player.source # Call set all zones service self.hass.services.call(DOMAIN, SERVICE_SETALLZONES, {'source': 'three'}, blocking=True) # Check that source was changed - self.assertEqual(3, self.blackbird.zones[3].av) + assert 3 == self.blackbird.zones[3].av self.media_player.update() - self.assertEqual('three', self.media_player.source) + assert 'three' == self.media_player.source def test_update(self): """Test updating values from blackbird.""" - self.assertIsNone(self.media_player.state) - self.assertIsNone(self.media_player.source) + assert self.media_player.state is None + assert self.media_player.source is None self.media_player.update() - self.assertEqual(STATE_ON, self.media_player.state) - self.assertEqual('one', self.media_player.source) + assert STATE_ON == self.media_player.state + assert 'one' == self.media_player.source def test_name(self): """Test name property.""" - self.assertEqual('Zone name', self.media_player.name) + assert 'Zone name' == self.media_player.name def test_state(self): """Test state property.""" - self.assertIsNone(self.media_player.state) + assert self.media_player.state is None self.media_player.update() - self.assertEqual(STATE_ON, self.media_player.state) + assert STATE_ON == self.media_player.state self.blackbird.zones[3].power = False self.media_player.update() - self.assertEqual(STATE_OFF, self.media_player.state) + assert STATE_OFF == self.media_player.state def test_supported_features(self): """Test supported features property.""" - self.assertEqual(SUPPORT_TURN_ON | SUPPORT_TURN_OFF | - SUPPORT_SELECT_SOURCE, - self.media_player.supported_features) + assert SUPPORT_TURN_ON | SUPPORT_TURN_OFF | \ + SUPPORT_SELECT_SOURCE == \ + self.media_player.supported_features def test_source(self): """Test source property.""" - self.assertIsNone(self.media_player.source) + assert self.media_player.source is None self.media_player.update() - self.assertEqual('one', self.media_player.source) + assert 'one' == self.media_player.source def test_media_title(self): """Test media title property.""" - self.assertIsNone(self.media_player.media_title) + assert self.media_player.media_title is None self.media_player.update() - self.assertEqual('one', self.media_player.media_title) + assert 'one' == self.media_player.media_title def test_source_list(self): """Test source list property.""" # Note, the list is sorted! - self.assertEqual(['one', 'two', 'three'], - self.media_player.source_list) + assert ['one', 'two', 'three'] == \ + self.media_player.source_list def test_select_source(self): """Test source selection methods.""" self.media_player.update() - self.assertEqual('one', self.media_player.source) + assert 'one' == self.media_player.source self.media_player.select_source('two') - self.assertEqual(2, self.blackbird.zones[3].av) + assert 2 == self.blackbird.zones[3].av self.media_player.update() - self.assertEqual('two', self.media_player.source) + assert 'two' == self.media_player.source # Trying to set unknown source. self.media_player.select_source('no name') - self.assertEqual(2, self.blackbird.zones[3].av) + assert 2 == self.blackbird.zones[3].av self.media_player.update() - self.assertEqual('two', self.media_player.source) + assert 'two' == self.media_player.source def test_turn_on(self): """Testing turning on the zone.""" self.blackbird.zones[3].power = False self.media_player.update() - self.assertEqual(STATE_OFF, self.media_player.state) + assert STATE_OFF == self.media_player.state self.media_player.turn_on() - self.assertTrue(self.blackbird.zones[3].power) + assert self.blackbird.zones[3].power self.media_player.update() - self.assertEqual(STATE_ON, self.media_player.state) + assert STATE_ON == self.media_player.state def test_turn_off(self): """Testing turning off the zone.""" self.blackbird.zones[3].power = True self.media_player.update() - self.assertEqual(STATE_ON, self.media_player.state) + assert STATE_ON == self.media_player.state self.media_player.turn_off() - self.assertFalse(self.blackbird.zones[3].power) + assert not self.blackbird.zones[3].power self.media_player.update() - self.assertEqual(STATE_OFF, self.media_player.state) + assert STATE_OFF == self.media_player.state diff --git a/tests/components/media_player/test_monoprice.py b/tests/components/media_player/test_monoprice.py index 14e176904..417cd4218 100644 --- a/tests/components/media_player/test_monoprice.py +++ b/tests/components/media_player/test_monoprice.py @@ -13,6 +13,7 @@ import tests.common from homeassistant.components.media_player.monoprice import ( DATA_MONOPRICE, PLATFORM_SCHEMA, SERVICE_SNAPSHOT, SERVICE_RESTORE, setup_platform) +import pytest class AttrDict(dict): @@ -149,7 +150,7 @@ class TestMonopriceSchema(unittest.TestCase): ) for value in schemas: - with self.assertRaises(vol.MultipleInvalid): + with pytest.raises(vol.MultipleInvalid): PLATFORM_SCHEMA(value) @@ -185,21 +186,19 @@ class TestMonopriceMediaPlayer(unittest.TestCase): def test_setup_platform(self, *args): """Test setting up platform.""" # Two services must be registered - self.assertTrue(self.hass.services.has_service(DOMAIN, - SERVICE_RESTORE)) - self.assertTrue(self.hass.services.has_service(DOMAIN, - SERVICE_SNAPSHOT)) - self.assertEqual(len(self.hass.data[DATA_MONOPRICE]), 1) - self.assertEqual(self.hass.data[DATA_MONOPRICE][0].name, 'Zone name') + assert self.hass.services.has_service(DOMAIN, SERVICE_RESTORE) + assert self.hass.services.has_service(DOMAIN, SERVICE_SNAPSHOT) + assert len(self.hass.data[DATA_MONOPRICE]) == 1 + assert self.hass.data[DATA_MONOPRICE][0].name == 'Zone name' def test_service_calls_with_entity_id(self): """Test snapshot save/restore service calls.""" self.media_player.update() - self.assertEqual('Zone name', self.media_player.name) - self.assertEqual(STATE_ON, self.media_player.state) - self.assertEqual(0.0, self.media_player.volume_level, 0.0001) - self.assertTrue(self.media_player.is_volume_muted) - self.assertEqual('one', self.media_player.source) + assert 'Zone name' == self.media_player.name + assert STATE_ON == self.media_player.state + assert 0.0 == self.media_player.volume_level, 0.0001 + assert self.media_player.is_volume_muted + assert 'one' == self.media_player.source # Saving default values self.hass.services.call(DOMAIN, SERVICE_SNAPSHOT, @@ -215,11 +214,11 @@ class TestMonopriceMediaPlayer(unittest.TestCase): # Checking that values were indeed changed self.media_player.update() - self.assertEqual('Zone name', self.media_player.name) - self.assertEqual(STATE_OFF, self.media_player.state) - self.assertEqual(1.0, self.media_player.volume_level, 0.0001) - self.assertFalse(self.media_player.is_volume_muted) - self.assertEqual('two', self.media_player.source) + assert 'Zone name' == self.media_player.name + assert STATE_OFF == self.media_player.state + assert 1.0 == self.media_player.volume_level, 0.0001 + assert not self.media_player.is_volume_muted + assert 'two' == self.media_player.source # Restoring wrong media player to its previous state # Nothing should be done @@ -230,11 +229,11 @@ class TestMonopriceMediaPlayer(unittest.TestCase): # Checking that values were not (!) restored self.media_player.update() - self.assertEqual('Zone name', self.media_player.name) - self.assertEqual(STATE_OFF, self.media_player.state) - self.assertEqual(1.0, self.media_player.volume_level, 0.0001) - self.assertFalse(self.media_player.is_volume_muted) - self.assertEqual('two', self.media_player.source) + assert 'Zone name' == self.media_player.name + assert STATE_OFF == self.media_player.state + assert 1.0 == self.media_player.volume_level, 0.0001 + assert not self.media_player.is_volume_muted + assert 'two' == self.media_player.source # Restoring media player to its previous state self.hass.services.call(DOMAIN, SERVICE_RESTORE, @@ -243,31 +242,31 @@ class TestMonopriceMediaPlayer(unittest.TestCase): self.hass.block_till_done() # Checking that values were restored - self.assertEqual('Zone name', self.media_player.name) - self.assertEqual(STATE_ON, self.media_player.state) - self.assertEqual(0.0, self.media_player.volume_level, 0.0001) - self.assertTrue(self.media_player.is_volume_muted) - self.assertEqual('one', self.media_player.source) + assert 'Zone name' == self.media_player.name + assert STATE_ON == self.media_player.state + assert 0.0 == self.media_player.volume_level, 0.0001 + assert self.media_player.is_volume_muted + assert 'one' == self.media_player.source def test_service_calls_without_entity_id(self): """Test snapshot save/restore service calls.""" self.media_player.update() - self.assertEqual('Zone name', self.media_player.name) - self.assertEqual(STATE_ON, self.media_player.state) - self.assertEqual(0.0, self.media_player.volume_level, 0.0001) - self.assertTrue(self.media_player.is_volume_muted) - self.assertEqual('one', self.media_player.source) + assert 'Zone name' == self.media_player.name + assert STATE_ON == self.media_player.state + assert 0.0 == self.media_player.volume_level, 0.0001 + assert self.media_player.is_volume_muted + assert 'one' == self.media_player.source # Restoring media player # since there is no snapshot, nothing should be done self.hass.services.call(DOMAIN, SERVICE_RESTORE, blocking=True) self.hass.block_till_done() self.media_player.update() - self.assertEqual('Zone name', self.media_player.name) - self.assertEqual(STATE_ON, self.media_player.state) - self.assertEqual(0.0, self.media_player.volume_level, 0.0001) - self.assertTrue(self.media_player.is_volume_muted) - self.assertEqual('one', self.media_player.source) + assert 'Zone name' == self.media_player.name + assert STATE_ON == self.media_player.state + assert 0.0 == self.media_player.volume_level, 0.0001 + assert self.media_player.is_volume_muted + assert 'one' == self.media_player.source # Saving default values self.hass.services.call(DOMAIN, SERVICE_SNAPSHOT, blocking=True) @@ -281,195 +280,195 @@ class TestMonopriceMediaPlayer(unittest.TestCase): # Checking that values were indeed changed self.media_player.update() - self.assertEqual('Zone name', self.media_player.name) - self.assertEqual(STATE_OFF, self.media_player.state) - self.assertEqual(1.0, self.media_player.volume_level, 0.0001) - self.assertFalse(self.media_player.is_volume_muted) - self.assertEqual('two', self.media_player.source) + assert 'Zone name' == self.media_player.name + assert STATE_OFF == self.media_player.state + assert 1.0 == self.media_player.volume_level, 0.0001 + assert not self.media_player.is_volume_muted + assert 'two' == self.media_player.source # Restoring media player to its previous state self.hass.services.call(DOMAIN, SERVICE_RESTORE, blocking=True) self.hass.block_till_done() # Checking that values were restored - self.assertEqual('Zone name', self.media_player.name) - self.assertEqual(STATE_ON, self.media_player.state) - self.assertEqual(0.0, self.media_player.volume_level, 0.0001) - self.assertTrue(self.media_player.is_volume_muted) - self.assertEqual('one', self.media_player.source) + assert 'Zone name' == self.media_player.name + assert STATE_ON == self.media_player.state + assert 0.0 == self.media_player.volume_level, 0.0001 + assert self.media_player.is_volume_muted + assert 'one' == self.media_player.source def test_update(self): """Test updating values from monoprice.""" - self.assertIsNone(self.media_player.state) - self.assertIsNone(self.media_player.volume_level) - self.assertIsNone(self.media_player.is_volume_muted) - self.assertIsNone(self.media_player.source) + assert self.media_player.state is None + assert self.media_player.volume_level is None + assert self.media_player.is_volume_muted is None + assert self.media_player.source is None self.media_player.update() - self.assertEqual(STATE_ON, self.media_player.state) - self.assertEqual(0.0, self.media_player.volume_level, 0.0001) - self.assertTrue(self.media_player.is_volume_muted) - self.assertEqual('one', self.media_player.source) + assert STATE_ON == self.media_player.state + assert 0.0 == self.media_player.volume_level, 0.0001 + assert self.media_player.is_volume_muted + assert 'one' == self.media_player.source def test_name(self): """Test name property.""" - self.assertEqual('Zone name', self.media_player.name) + assert 'Zone name' == self.media_player.name def test_state(self): """Test state property.""" - self.assertIsNone(self.media_player.state) + assert self.media_player.state is None self.media_player.update() - self.assertEqual(STATE_ON, self.media_player.state) + assert STATE_ON == self.media_player.state self.monoprice.zones[12].power = False self.media_player.update() - self.assertEqual(STATE_OFF, self.media_player.state) + assert STATE_OFF == self.media_player.state def test_volume_level(self): """Test volume level property.""" - self.assertIsNone(self.media_player.volume_level) + assert self.media_player.volume_level is None self.media_player.update() - self.assertEqual(0.0, self.media_player.volume_level, 0.0001) + assert 0.0 == self.media_player.volume_level, 0.0001 self.monoprice.zones[12].volume = 38 self.media_player.update() - self.assertEqual(1.0, self.media_player.volume_level, 0.0001) + assert 1.0 == self.media_player.volume_level, 0.0001 self.monoprice.zones[12].volume = 19 self.media_player.update() - self.assertEqual(.5, self.media_player.volume_level, 0.0001) + assert .5 == self.media_player.volume_level, 0.0001 def test_is_volume_muted(self): """Test volume muted property.""" - self.assertIsNone(self.media_player.is_volume_muted) + assert self.media_player.is_volume_muted is None self.media_player.update() - self.assertTrue(self.media_player.is_volume_muted) + assert self.media_player.is_volume_muted self.monoprice.zones[12].mute = False self.media_player.update() - self.assertFalse(self.media_player.is_volume_muted) + assert not self.media_player.is_volume_muted def test_supported_features(self): """Test supported features property.""" - self.assertEqual(SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET | - SUPPORT_VOLUME_STEP | SUPPORT_TURN_ON | - SUPPORT_TURN_OFF | SUPPORT_SELECT_SOURCE, - self.media_player.supported_features) + assert SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET | \ + SUPPORT_VOLUME_STEP | SUPPORT_TURN_ON | \ + SUPPORT_TURN_OFF | SUPPORT_SELECT_SOURCE == \ + self.media_player.supported_features def test_source(self): """Test source property.""" - self.assertIsNone(self.media_player.source) + assert self.media_player.source is None self.media_player.update() - self.assertEqual('one', self.media_player.source) + assert 'one' == self.media_player.source def test_media_title(self): """Test media title property.""" - self.assertIsNone(self.media_player.media_title) + assert self.media_player.media_title is None self.media_player.update() - self.assertEqual('one', self.media_player.media_title) + assert 'one' == self.media_player.media_title def test_source_list(self): """Test source list property.""" # Note, the list is sorted! - self.assertEqual(['one', 'two', 'three'], - self.media_player.source_list) + assert ['one', 'two', 'three'] == \ + self.media_player.source_list def test_select_source(self): """Test source selection methods.""" self.media_player.update() - self.assertEqual('one', self.media_player.source) + assert 'one' == self.media_player.source self.media_player.select_source('two') - self.assertEqual(2, self.monoprice.zones[12].source) + assert 2 == self.monoprice.zones[12].source self.media_player.update() - self.assertEqual('two', self.media_player.source) + assert 'two' == self.media_player.source # Trying to set unknown source self.media_player.select_source('no name') - self.assertEqual(2, self.monoprice.zones[12].source) + assert 2 == self.monoprice.zones[12].source self.media_player.update() - self.assertEqual('two', self.media_player.source) + assert 'two' == self.media_player.source def test_turn_on(self): """Test turning on the zone.""" self.monoprice.zones[12].power = False self.media_player.update() - self.assertEqual(STATE_OFF, self.media_player.state) + assert STATE_OFF == self.media_player.state self.media_player.turn_on() - self.assertTrue(self.monoprice.zones[12].power) + assert self.monoprice.zones[12].power self.media_player.update() - self.assertEqual(STATE_ON, self.media_player.state) + assert STATE_ON == self.media_player.state def test_turn_off(self): """Test turning off the zone.""" self.monoprice.zones[12].power = True self.media_player.update() - self.assertEqual(STATE_ON, self.media_player.state) + assert STATE_ON == self.media_player.state self.media_player.turn_off() - self.assertFalse(self.monoprice.zones[12].power) + assert not self.monoprice.zones[12].power self.media_player.update() - self.assertEqual(STATE_OFF, self.media_player.state) + assert STATE_OFF == self.media_player.state def test_mute_volume(self): """Test mute functionality.""" self.monoprice.zones[12].mute = True self.media_player.update() - self.assertTrue(self.media_player.is_volume_muted) + assert self.media_player.is_volume_muted self.media_player.mute_volume(False) - self.assertFalse(self.monoprice.zones[12].mute) + assert not self.monoprice.zones[12].mute self.media_player.update() - self.assertFalse(self.media_player.is_volume_muted) + assert not self.media_player.is_volume_muted self.media_player.mute_volume(True) - self.assertTrue(self.monoprice.zones[12].mute) + assert self.monoprice.zones[12].mute self.media_player.update() - self.assertTrue(self.media_player.is_volume_muted) + assert self.media_player.is_volume_muted def test_set_volume_level(self): """Test set volume level.""" self.media_player.set_volume_level(1.0) - self.assertEqual(38, self.monoprice.zones[12].volume) - self.assertTrue(isinstance(self.monoprice.zones[12].volume, int)) + assert 38 == self.monoprice.zones[12].volume + assert isinstance(self.monoprice.zones[12].volume, int) self.media_player.set_volume_level(0.0) - self.assertEqual(0, self.monoprice.zones[12].volume) - self.assertTrue(isinstance(self.monoprice.zones[12].volume, int)) + assert 0 == self.monoprice.zones[12].volume + assert isinstance(self.monoprice.zones[12].volume, int) self.media_player.set_volume_level(0.5) - self.assertEqual(19, self.monoprice.zones[12].volume) - self.assertTrue(isinstance(self.monoprice.zones[12].volume, int)) + assert 19 == self.monoprice.zones[12].volume + assert isinstance(self.monoprice.zones[12].volume, int) def test_volume_up(self): """Test increasing volume by one.""" self.monoprice.zones[12].volume = 37 self.media_player.update() self.media_player.volume_up() - self.assertEqual(38, self.monoprice.zones[12].volume) - self.assertTrue(isinstance(self.monoprice.zones[12].volume, int)) + assert 38 == self.monoprice.zones[12].volume + assert isinstance(self.monoprice.zones[12].volume, int) # Try to raise value beyond max self.media_player.update() self.media_player.volume_up() - self.assertEqual(38, self.monoprice.zones[12].volume) - self.assertTrue(isinstance(self.monoprice.zones[12].volume, int)) + assert 38 == self.monoprice.zones[12].volume + assert isinstance(self.monoprice.zones[12].volume, int) def test_volume_down(self): """Test decreasing volume by one.""" self.monoprice.zones[12].volume = 1 self.media_player.update() self.media_player.volume_down() - self.assertEqual(0, self.monoprice.zones[12].volume) - self.assertTrue(isinstance(self.monoprice.zones[12].volume, int)) + assert 0 == self.monoprice.zones[12].volume + assert isinstance(self.monoprice.zones[12].volume, int) # Try to lower value beyond minimum self.media_player.update() self.media_player.volume_down() - self.assertEqual(0, self.monoprice.zones[12].volume) - self.assertTrue(isinstance(self.monoprice.zones[12].volume, int)) + assert 0 == self.monoprice.zones[12].volume + assert isinstance(self.monoprice.zones[12].volume, int) diff --git a/tests/components/media_player/test_samsungtv.py b/tests/components/media_player/test_samsungtv.py index dda6562af..31ad44925 100644 --- a/tests/components/media_player/test_samsungtv.py +++ b/tests/components/media_player/test_samsungtv.py @@ -102,7 +102,7 @@ class TestSamsungTv(unittest.TestCase): def test_update_on(self): """Testing update tv on.""" self.device.update() - self.assertEqual(None, self.device._state) + assert self.device._state is None def test_update_off(self): """Testing update tv off.""" @@ -111,12 +111,12 @@ class TestSamsungTv(unittest.TestCase): side_effect=OSError('Boom')) self.device.get_remote = mock.Mock(return_value=_remote) self.device.update() - self.assertEqual(STATE_OFF, self.device._state) + assert STATE_OFF == self.device._state def test_send_key(self): """Test for send key.""" self.device.send_key('KEY_POWER') - self.assertEqual(None, self.device._state) + assert self.device._state is None def test_send_key_broken_pipe(self): """Testing broken pipe Exception.""" @@ -125,8 +125,8 @@ class TestSamsungTv(unittest.TestCase): side_effect=BrokenPipeError('Boom')) self.device.get_remote = mock.Mock(return_value=_remote) self.device.send_key('HELLO') - self.assertIsNone(self.device._remote) - self.assertEqual(None, self.device._state) + assert self.device._remote is None + assert self.device._state is None def test_send_key_connection_closed_retry_succeed(self): """Test retry on connection closed.""" @@ -137,11 +137,11 @@ class TestSamsungTv(unittest.TestCase): self.device.get_remote = mock.Mock(return_value=_remote) command = 'HELLO' self.device.send_key(command) - self.assertEqual(None, self.device._state) + assert self.device._state is None # verify that _remote.control() get called twice because of retry logic expected = [mock.call(command), mock.call(command)] - self.assertEqual(expected, _remote.control.call_args_list) + assert expected == _remote.control.call_args_list def test_send_key_unhandled_response(self): """Testing unhandled response exception.""" @@ -151,8 +151,8 @@ class TestSamsungTv(unittest.TestCase): ) self.device.get_remote = mock.Mock(return_value=_remote) self.device.send_key('HELLO') - self.assertIsNone(self.device._remote) - self.assertEqual(None, self.device._state) + assert self.device._remote is None + assert self.device._state is None def test_send_key_os_error(self): """Testing broken pipe Exception.""" @@ -161,42 +161,41 @@ class TestSamsungTv(unittest.TestCase): side_effect=OSError('Boom')) self.device.get_remote = mock.Mock(return_value=_remote) self.device.send_key('HELLO') - self.assertIsNone(self.device._remote) - self.assertEqual(STATE_OFF, self.device._state) + assert self.device._remote is None + assert STATE_OFF == self.device._state def test_power_off_in_progress(self): """Test for power_off_in_progress.""" - self.assertFalse(self.device._power_off_in_progress()) + assert not self.device._power_off_in_progress() self.device._end_of_power_off = dt_util.utcnow() + timedelta( seconds=15) - self.assertTrue(self.device._power_off_in_progress()) + assert self.device._power_off_in_progress() def test_name(self): """Test for name property.""" - self.assertEqual('fake', self.device.name) + assert 'fake' == self.device.name def test_state(self): """Test for state property.""" self.device._state = None - self.assertEqual(None, self.device.state) + assert self.device.state is None self.device._state = STATE_OFF - self.assertEqual(STATE_OFF, self.device.state) + assert STATE_OFF == self.device.state def test_is_volume_muted(self): """Test for is_volume_muted property.""" self.device._muted = False - self.assertFalse(self.device.is_volume_muted) + assert not self.device.is_volume_muted self.device._muted = True - self.assertTrue(self.device.is_volume_muted) + assert self.device.is_volume_muted def test_supported_features(self): """Test for supported_features property.""" self.device._mac = None - self.assertEqual(SUPPORT_SAMSUNGTV, self.device.supported_features) + assert SUPPORT_SAMSUNGTV == self.device.supported_features self.device._mac = "fake" - self.assertEqual( - SUPPORT_SAMSUNGTV | SUPPORT_TURN_ON, - self.device.supported_features) + assert SUPPORT_SAMSUNGTV | SUPPORT_TURN_ON == \ + self.device.supported_features def test_turn_off(self): """Test for turn_off.""" @@ -206,7 +205,7 @@ class TestSamsungTv(unittest.TestCase): self.get_remote = mock.Mock(return_value=_remote) self.device._end_of_power_off = None self.device.turn_off() - self.assertIsNotNone(self.device._end_of_power_off) + assert self.device._end_of_power_off is not None self.device.send_key.assert_called_once_with('KEY_POWER') self.device.send_key = mock.Mock() self.device._config['method'] = 'legacy' @@ -247,11 +246,11 @@ class TestSamsungTv(unittest.TestCase): self.device._playing = False self.device.media_play_pause() self.device.send_key.assert_called_once_with("KEY_PLAY") - self.assertTrue(self.device._playing) + assert self.device._playing self.device.send_key = mock.Mock() self.device.media_play_pause() self.device.send_key.assert_called_once_with("KEY_PAUSE") - self.assertFalse(self.device._playing) + assert not self.device._playing def test_media_play(self): """Test for media_play.""" @@ -259,7 +258,7 @@ class TestSamsungTv(unittest.TestCase): self.device._playing = False self.device.media_play() self.device.send_key.assert_called_once_with("KEY_PLAY") - self.assertTrue(self.device._playing) + assert self.device._playing def test_media_pause(self): """Test for media_pause.""" @@ -267,7 +266,7 @@ class TestSamsungTv(unittest.TestCase): self.device._playing = True self.device.media_pause() self.device.send_key.assert_called_once_with("KEY_PAUSE") - self.assertFalse(self.device._playing) + assert not self.device._playing def test_media_next_track(self): """Test for media_next_track.""" diff --git a/tests/components/media_player/test_sonos.py b/tests/components/media_player/test_sonos.py index cfe969a25..bf81aee59 100644 --- a/tests/components/media_player/test_sonos.py +++ b/tests/components/media_player/test_sonos.py @@ -162,8 +162,8 @@ class TestSonosMediaPlayer(unittest.TestCase): }) devices = list(self.hass.data[sonos.DATA_SONOS].devices) - self.assertEqual(len(devices), 1) - self.assertEqual(devices[0].name, 'Kitchen') + assert len(devices) == 1 + assert devices[0].name == 'Kitchen' @mock.patch('pysonos.SoCo', new=SoCoMock) @mock.patch('socket.create_connection', side_effect=socket.error()) @@ -181,8 +181,8 @@ class TestSonosMediaPlayer(unittest.TestCase): assert setup_component(self.hass, DOMAIN, config) - self.assertEqual(len(self.hass.data[sonos.DATA_SONOS].devices), 1) - self.assertEqual(discover_mock.call_count, 1) + assert len(self.hass.data[sonos.DATA_SONOS].devices) == 1 + assert discover_mock.call_count == 1 @mock.patch('pysonos.SoCo', new=SoCoMock) @mock.patch('socket.create_connection', side_effect=socket.error()) @@ -198,8 +198,8 @@ class TestSonosMediaPlayer(unittest.TestCase): assert setup_component(self.hass, DOMAIN, config) devices = self.hass.data[sonos.DATA_SONOS].devices - self.assertEqual(len(devices), 1) - self.assertEqual(devices[0].name, 'Kitchen') + assert len(devices) == 1 + assert devices[0].name == 'Kitchen' @mock.patch('pysonos.SoCo', new=SoCoMock) @mock.patch('socket.create_connection', side_effect=socket.error()) @@ -215,8 +215,8 @@ class TestSonosMediaPlayer(unittest.TestCase): assert setup_component(self.hass, DOMAIN, config) devices = self.hass.data[sonos.DATA_SONOS].devices - self.assertEqual(len(devices), 2) - self.assertEqual(devices[0].name, 'Kitchen') + assert len(devices) == 2 + assert devices[0].name == 'Kitchen' @mock.patch('pysonos.SoCo', new=SoCoMock) @mock.patch('socket.create_connection', side_effect=socket.error()) @@ -232,8 +232,8 @@ class TestSonosMediaPlayer(unittest.TestCase): assert setup_component(self.hass, DOMAIN, config) devices = self.hass.data[sonos.DATA_SONOS].devices - self.assertEqual(len(devices), 2) - self.assertEqual(devices[0].name, 'Kitchen') + assert len(devices) == 2 + assert devices[0].name == 'Kitchen' @mock.patch('pysonos.SoCo', new=SoCoMock) @mock.patch.object(pysonos, 'discover', new=pysonosDiscoverMock.discover) @@ -242,8 +242,8 @@ class TestSonosMediaPlayer(unittest.TestCase): """Test a single device using the autodiscovery provided by Sonos.""" sonos.setup_platform(self.hass, {}, add_entities_factory(self.hass)) devices = list(self.hass.data[sonos.DATA_SONOS].devices) - self.assertEqual(len(devices), 1) - self.assertEqual(devices[0].name, 'Kitchen') + assert len(devices) == 1 + assert devices[0].name == 'Kitchen' @mock.patch('pysonos.SoCo', new=SoCoMock) @mock.patch('socket.create_connection', side_effect=socket.error()) @@ -296,11 +296,11 @@ class TestSonosMediaPlayer(unittest.TestCase): device.set_alarm(alarm_id=2) alarm1.save.assert_not_called() device.set_alarm(alarm_id=1, **attrs) - self.assertEqual(alarm1.enabled, attrs['enabled']) - self.assertEqual(alarm1.start_time, attrs['time']) - self.assertEqual(alarm1.include_linked_zones, - attrs['include_linked_zones']) - self.assertEqual(alarm1.volume, 30) + assert alarm1.enabled == attrs['enabled'] + assert alarm1.start_time == attrs['time'] + assert alarm1.include_linked_zones == \ + attrs['include_linked_zones'] + assert alarm1.volume == 30 alarm1.save.assert_called_once_with() @mock.patch('pysonos.SoCo', new=SoCoMock) @@ -316,8 +316,8 @@ class TestSonosMediaPlayer(unittest.TestCase): snapshotMock.return_value = True device.snapshot() - self.assertEqual(snapshotMock.call_count, 1) - self.assertEqual(snapshotMock.call_args, mock.call()) + assert snapshotMock.call_count == 1 + assert snapshotMock.call_args == mock.call() @mock.patch('pysonos.SoCo', new=SoCoMock) @mock.patch('socket.create_connection', side_effect=socket.error()) @@ -337,5 +337,5 @@ class TestSonosMediaPlayer(unittest.TestCase): device._snapshot_coordinator.soco_device = SoCoMock('192.0.2.17') device._soco_snapshot = Snapshot(device._player) device.restore() - self.assertEqual(restoreMock.call_count, 1) - self.assertEqual(restoreMock.call_args, mock.call(False)) + assert restoreMock.call_count == 1 + assert restoreMock.call_args == mock.call(False) diff --git a/tests/components/media_player/test_soundtouch.py b/tests/components/media_player/test_soundtouch.py index 62356e6af..2a763bfc7 100644 --- a/tests/components/media_player/test_soundtouch.py +++ b/tests/components/media_player/test_soundtouch.py @@ -164,10 +164,10 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): default_component(), mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(len(all_devices), 1) - self.assertEqual(all_devices[0].name, 'soundtouch') - self.assertEqual(all_devices[0].config['port'], 8090) - self.assertEqual(mocked_soundtouch_device.call_count, 1) + assert len(all_devices) == 1 + assert all_devices[0].name == 'soundtouch' + assert all_devices[0].config['port'] == 8090 + assert mocked_soundtouch_device.call_count == 1 @mock.patch('libsoundtouch.soundtouch_device', side_effect=None) def test_ensure_setup_discovery(self, mocked_soundtouch_device): @@ -181,10 +181,10 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock(), new_device) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(len(all_devices), 1) - self.assertEqual(all_devices[0].config['port'], 8090) - self.assertEqual(all_devices[0].config['host'], '192.168.1.1') - self.assertEqual(mocked_soundtouch_device.call_count, 1) + assert len(all_devices) == 1 + assert all_devices[0].config['port'] == 8090 + assert all_devices[0].config['host'] == '192.168.1.1' + assert mocked_soundtouch_device.call_count == 1 @mock.patch('libsoundtouch.soundtouch_device', side_effect=None) def test_ensure_setup_discovery_no_duplicate(self, @@ -193,7 +193,7 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): soundtouch.setup_platform(self.hass, default_component(), mock.MagicMock()) - self.assertEqual(len(self.hass.data[soundtouch.DATA_SOUNDTOUCH]), 1) + assert len(self.hass.data[soundtouch.DATA_SOUNDTOUCH]) == 1 new_device = {"port": "8090", "host": "192.168.1.1", "properties": {}, @@ -203,7 +203,7 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock(), new_device # New device ) - self.assertEqual(len(self.hass.data[soundtouch.DATA_SOUNDTOUCH]), 2) + assert len(self.hass.data[soundtouch.DATA_SOUNDTOUCH]) == 2 existing_device = {"port": "8090", "host": "192.168.0.1", "properties": {}, @@ -213,8 +213,8 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock(), existing_device # Existing device ) - self.assertEqual(mocked_soundtouch_device.call_count, 2) - self.assertEqual(len(self.hass.data[soundtouch.DATA_SOUNDTOUCH]), 2) + assert mocked_soundtouch_device.call_count == 2 + assert len(self.hass.data[soundtouch.DATA_SOUNDTOUCH]) == 2 @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @mock.patch('libsoundtouch.device.SoundTouchDevice.status') @@ -226,12 +226,12 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): soundtouch.setup_platform(self.hass, default_component(), mock.MagicMock()) - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 1 self.hass.data[soundtouch.DATA_SOUNDTOUCH][0].update() - self.assertEqual(mocked_status.call_count, 2) - self.assertEqual(mocked_volume.call_count, 2) + assert mocked_status.call_count == 2 + assert mocked_volume.call_count == 2 @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @mock.patch('libsoundtouch.device.SoundTouchDevice.status', @@ -244,17 +244,17 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): soundtouch.setup_platform(self.hass, default_component(), mock.MagicMock()) - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 1 all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(all_devices[0].state, STATE_PLAYING) - self.assertEqual(all_devices[0].media_image_url, "image.url") - self.assertEqual(all_devices[0].media_title, "artist - track") - self.assertEqual(all_devices[0].media_track, "track") - self.assertEqual(all_devices[0].media_artist, "artist") - self.assertEqual(all_devices[0].media_album_name, "album") - self.assertEqual(all_devices[0].media_duration, 1) + assert all_devices[0].state == STATE_PLAYING + assert all_devices[0].media_image_url == "image.url" + assert all_devices[0].media_title == "artist - track" + assert all_devices[0].media_track == "track" + assert all_devices[0].media_artist == "artist" + assert all_devices[0].media_album_name == "album" + assert all_devices[0].media_duration == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @mock.patch('libsoundtouch.device.SoundTouchDevice.status', @@ -267,11 +267,11 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): soundtouch.setup_platform(self.hass, default_component(), mock.MagicMock()) - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 1 all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(all_devices[0].media_title, None) + assert all_devices[0].media_title is None @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @mock.patch('libsoundtouch.device.SoundTouchDevice.status', @@ -284,17 +284,17 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): soundtouch.setup_platform(self.hass, default_component(), mock.MagicMock()) - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 1 all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(all_devices[0].state, STATE_PLAYING) - self.assertEqual(all_devices[0].media_image_url, "image.url") - self.assertEqual(all_devices[0].media_title, "station") - self.assertEqual(all_devices[0].media_track, None) - self.assertEqual(all_devices[0].media_artist, None) - self.assertEqual(all_devices[0].media_album_name, None) - self.assertEqual(all_devices[0].media_duration, None) + assert all_devices[0].state == STATE_PLAYING + assert all_devices[0].media_image_url == "image.url" + assert all_devices[0].media_title == "station" + assert all_devices[0].media_track is None + assert all_devices[0].media_artist is None + assert all_devices[0].media_album_name is None + assert all_devices[0].media_duration is None @mock.patch('libsoundtouch.device.SoundTouchDevice.volume', side_effect=MockVolume) @@ -307,11 +307,11 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): soundtouch.setup_platform(self.hass, default_component(), mock.MagicMock()) - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 1 all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(all_devices[0].volume_level, 0.12) + assert all_devices[0].volume_level == 0.12 @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @mock.patch('libsoundtouch.device.SoundTouchDevice.status', @@ -324,11 +324,11 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): soundtouch.setup_platform(self.hass, default_component(), mock.MagicMock()) - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 1 all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(all_devices[0].state, STATE_OFF) + assert all_devices[0].state == STATE_OFF @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @mock.patch('libsoundtouch.device.SoundTouchDevice.status', @@ -341,11 +341,11 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): soundtouch.setup_platform(self.hass, default_component(), mock.MagicMock()) - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 1 all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(all_devices[0].state, STATE_PAUSED) + assert all_devices[0].state == STATE_PAUSED @mock.patch('libsoundtouch.device.SoundTouchDevice.volume', side_effect=MockVolumeMuted) @@ -358,11 +358,11 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): soundtouch.setup_platform(self.hass, default_component(), mock.MagicMock()) - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 1 all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(all_devices[0].is_volume_muted, True) + assert all_devices[0].is_volume_muted is True @mock.patch('libsoundtouch.soundtouch_device') def test_media_commands(self, mocked_soundtouch_device): @@ -370,9 +370,9 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): soundtouch.setup_platform(self.hass, default_component(), mock.MagicMock()) - self.assertEqual(mocked_soundtouch_device.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(all_devices[0].supported_features, 17853) + assert all_devices[0].supported_features == 17853 @mock.patch('libsoundtouch.device.SoundTouchDevice.power_off') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -387,10 +387,10 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].turn_off() - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 2) - self.assertEqual(mocked_volume.call_count, 1) - self.assertEqual(mocked_power_off.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 2 + assert mocked_volume.call_count == 1 + assert mocked_power_off.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.power_on') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -405,10 +405,10 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].turn_on() - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 2) - self.assertEqual(mocked_volume.call_count, 1) - self.assertEqual(mocked_power_on.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 2 + assert mocked_volume.call_count == 1 + assert mocked_power_on.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.volume_up') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -423,10 +423,10 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].volume_up() - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 2) - self.assertEqual(mocked_volume_up.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 2 + assert mocked_volume_up.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.volume_down') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -441,10 +441,10 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].volume_down() - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 2) - self.assertEqual(mocked_volume_down.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 2 + assert mocked_volume_down.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.set_volume') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -459,9 +459,9 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].set_volume_level(0.17) - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 2) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 2 mocked_set_volume.assert_called_with(17) @mock.patch('libsoundtouch.device.SoundTouchDevice.mute') @@ -477,10 +477,10 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].mute_volume(None) - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 2) - self.assertEqual(mocked_mute.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 2 + assert mocked_mute.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.play') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -495,10 +495,10 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].media_play() - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 2) - self.assertEqual(mocked_volume.call_count, 1) - self.assertEqual(mocked_play.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 2 + assert mocked_volume.call_count == 1 + assert mocked_play.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.pause') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -513,10 +513,10 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].media_pause() - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 2) - self.assertEqual(mocked_volume.call_count, 1) - self.assertEqual(mocked_pause.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 2 + assert mocked_volume.call_count == 1 + assert mocked_pause.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.play_pause') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -531,10 +531,10 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].media_play_pause() - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 2) - self.assertEqual(mocked_volume.call_count, 1) - self.assertEqual(mocked_play_pause.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 2 + assert mocked_volume.call_count == 1 + assert mocked_play_pause.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.previous_track') @mock.patch('libsoundtouch.device.SoundTouchDevice.next_track') @@ -550,15 +550,15 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): default_component(), mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 1 all_devices[0].media_next_track() - self.assertEqual(mocked_status.call_count, 2) - self.assertEqual(mocked_next_track.call_count, 1) + assert mocked_status.call_count == 2 + assert mocked_next_track.call_count == 1 all_devices[0].media_previous_track() - self.assertEqual(mocked_status.call_count, 3) - self.assertEqual(mocked_previous_track.call_count, 1) + assert mocked_status.call_count == 3 + assert mocked_previous_track.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.select_preset') @mock.patch('libsoundtouch.device.SoundTouchDevice.presets', @@ -574,15 +574,15 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): default_component(), mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 1 all_devices[0].play_media('PLAYLIST', 1) - self.assertEqual(mocked_presets.call_count, 1) - self.assertEqual(mocked_select_preset.call_count, 1) + assert mocked_presets.call_count == 1 + assert mocked_select_preset.call_count == 1 all_devices[0].play_media('PLAYLIST', 2) - self.assertEqual(mocked_presets.call_count, 2) - self.assertEqual(mocked_select_preset.call_count, 1) + assert mocked_presets.call_count == 2 + assert mocked_select_preset.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.play_url') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -596,9 +596,9 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): default_component(), mock.MagicMock()) all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] - self.assertEqual(mocked_soundtouch_device.call_count, 1) - self.assertEqual(mocked_status.call_count, 1) - self.assertEqual(mocked_volume.call_count, 1) + assert mocked_soundtouch_device.call_count == 1 + assert mocked_status.call_count == 1 + assert mocked_volume.call_count == 1 all_devices[0].play_media('MUSIC', "http://fqdn/file.mp3") mocked_play_url.assert_called_with("http://fqdn/file.mp3") @@ -619,28 +619,28 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].entity_id = "media_player.entity_1" all_devices[1].entity_id = "media_player.entity_2" - self.assertEqual(mocked_soundtouch_device.call_count, 2) - self.assertEqual(mocked_status.call_count, 2) - self.assertEqual(mocked_volume.call_count, 2) + assert mocked_soundtouch_device.call_count == 2 + assert mocked_status.call_count == 2 + assert mocked_volume.call_count == 2 # one master, one slave => create zone self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_PLAY_EVERYWHERE, {"master": "media_player.entity_1"}, True) - self.assertEqual(mocked_create_zone.call_count, 1) + assert mocked_create_zone.call_count == 1 # unknown master. create zone is must not be called self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_PLAY_EVERYWHERE, {"master": "media_player.entity_X"}, True) - self.assertEqual(mocked_create_zone.call_count, 1) + assert mocked_create_zone.call_count == 1 # no slaves, create zone must not be called all_devices.pop(1) self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_PLAY_EVERYWHERE, {"master": "media_player.entity_1"}, True) - self.assertEqual(mocked_create_zone.call_count, 1) + assert mocked_create_zone.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.create_zone') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -659,30 +659,30 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].entity_id = "media_player.entity_1" all_devices[1].entity_id = "media_player.entity_2" - self.assertEqual(mocked_soundtouch_device.call_count, 2) - self.assertEqual(mocked_status.call_count, 2) - self.assertEqual(mocked_volume.call_count, 2) + assert mocked_soundtouch_device.call_count == 2 + assert mocked_status.call_count == 2 + assert mocked_volume.call_count == 2 # one master, one slave => create zone self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_CREATE_ZONE, {"master": "media_player.entity_1", "slaves": ["media_player.entity_2"]}, True) - self.assertEqual(mocked_create_zone.call_count, 1) + assert mocked_create_zone.call_count == 1 # unknown master. create zone is must not be called self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_CREATE_ZONE, {"master": "media_player.entity_X", "slaves": ["media_player.entity_2"]}, True) - self.assertEqual(mocked_create_zone.call_count, 1) + assert mocked_create_zone.call_count == 1 # no slaves, create zone must not be called self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_CREATE_ZONE, {"master": "media_player.entity_X", "slaves": []}, True) - self.assertEqual(mocked_create_zone.call_count, 1) + assert mocked_create_zone.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.remove_zone_slave') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -701,30 +701,30 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].entity_id = "media_player.entity_1" all_devices[1].entity_id = "media_player.entity_2" - self.assertEqual(mocked_soundtouch_device.call_count, 2) - self.assertEqual(mocked_status.call_count, 2) - self.assertEqual(mocked_volume.call_count, 2) + assert mocked_soundtouch_device.call_count == 2 + assert mocked_status.call_count == 2 + assert mocked_volume.call_count == 2 # remove one slave self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_REMOVE_ZONE_SLAVE, {"master": "media_player.entity_1", "slaves": ["media_player.entity_2"]}, True) - self.assertEqual(mocked_remove_zone_slave.call_count, 1) + assert mocked_remove_zone_slave.call_count == 1 # unknown master. add zone slave is not called self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_REMOVE_ZONE_SLAVE, {"master": "media_player.entity_X", "slaves": ["media_player.entity_2"]}, True) - self.assertEqual(mocked_remove_zone_slave.call_count, 1) + assert mocked_remove_zone_slave.call_count == 1 # no slave to add, add zone slave is not called self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_REMOVE_ZONE_SLAVE, {"master": "media_player.entity_1", "slaves": []}, True) - self.assertEqual(mocked_remove_zone_slave.call_count, 1) + assert mocked_remove_zone_slave.call_count == 1 @mock.patch('libsoundtouch.device.SoundTouchDevice.add_zone_slave') @mock.patch('libsoundtouch.device.SoundTouchDevice.volume') @@ -743,27 +743,27 @@ class TestSoundtouchMediaPlayer(unittest.TestCase): all_devices = self.hass.data[soundtouch.DATA_SOUNDTOUCH] all_devices[0].entity_id = "media_player.entity_1" all_devices[1].entity_id = "media_player.entity_2" - self.assertEqual(mocked_soundtouch_device.call_count, 2) - self.assertEqual(mocked_status.call_count, 2) - self.assertEqual(mocked_volume.call_count, 2) + assert mocked_soundtouch_device.call_count == 2 + assert mocked_status.call_count == 2 + assert mocked_volume.call_count == 2 # add one slave self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_ADD_ZONE_SLAVE, {"master": "media_player.entity_1", "slaves": ["media_player.entity_2"]}, True) - self.assertEqual(mocked_add_zone_slave.call_count, 1) + assert mocked_add_zone_slave.call_count == 1 # unknown master. add zone slave is not called self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_ADD_ZONE_SLAVE, {"master": "media_player.entity_X", "slaves": ["media_player.entity_2"]}, True) - self.assertEqual(mocked_add_zone_slave.call_count, 1) + assert mocked_add_zone_slave.call_count == 1 # no slave to add, add zone slave is not called self.hass.services.call(soundtouch.DOMAIN, soundtouch.SERVICE_ADD_ZONE_SLAVE, {"master": "media_player.entity_1", "slaves": ["media_player.entity_X"]}, True) - self.assertEqual(mocked_add_zone_slave.call_count, 1) + assert mocked_add_zone_slave.call_count == 1 diff --git a/tests/components/media_player/test_universal.py b/tests/components/media_player/test_universal.py index 279809a28..9f0f6d072 100644 --- a/tests/components/media_player/test_universal.py +++ b/tests/components/media_player/test_universal.py @@ -220,7 +220,7 @@ class TestMediaPlayer(unittest.TestCase): config_start['attributes'] = {} config = validate_config(self.config_children_only) - self.assertEqual(config_start, config) + assert config_start == config def test_config_children_and_attr(self): """Check config with children and attributes.""" @@ -229,7 +229,7 @@ class TestMediaPlayer(unittest.TestCase): config_start['commands'] = {} config = validate_config(self.config_children_and_attr) - self.assertEqual(config_start, config) + assert config_start == config def test_config_no_name(self): """Check config with no Name entry.""" @@ -238,7 +238,7 @@ class TestMediaPlayer(unittest.TestCase): validate_config({'platform': 'universal'}) except MultipleInvalid: response = False - self.assertFalse(response) + assert not response def test_config_bad_children(self): """Check config with bad children entry.""" @@ -247,31 +247,31 @@ class TestMediaPlayer(unittest.TestCase): 'platform': 'universal'} config_no_children = validate_config(config_no_children) - self.assertEqual([], config_no_children['children']) + assert [] == config_no_children['children'] config_bad_children = validate_config(config_bad_children) - self.assertEqual([], config_bad_children['children']) + assert [] == config_bad_children['children'] def test_config_bad_commands(self): """Check config with bad commands entry.""" config = {'name': 'test', 'platform': 'universal'} config = validate_config(config) - self.assertEqual({}, config['commands']) + assert {} == config['commands'] def test_config_bad_attributes(self): """Check config with bad attributes.""" config = {'name': 'test', 'platform': 'universal'} config = validate_config(config) - self.assertEqual({}, config['attributes']) + assert {} == config['attributes'] def test_config_bad_key(self): """Check config with bad key.""" config = {'name': 'test', 'asdf': 5, 'platform': 'universal'} config = validate_config(config) - self.assertFalse('asdf' in config) + assert not ('asdf' in config) def test_platform_setup(self): """Test platform setup.""" @@ -292,15 +292,15 @@ class TestMediaPlayer(unittest.TestCase): self.hass.loop).result() except MultipleInvalid: setup_ok = False - self.assertFalse(setup_ok) - self.assertEqual(0, len(entities)) + assert not setup_ok + assert 0 == len(entities) run_coroutine_threadsafe( universal.async_setup_platform( self.hass, validate_config(config), add_entities), self.hass.loop).result() - self.assertEqual(1, len(entities)) - self.assertEqual('test', entities[0].name) + assert 1 == len(entities) + assert 'test' == entities[0].name def test_master_state(self): """Test master state property.""" @@ -308,7 +308,7 @@ class TestMediaPlayer(unittest.TestCase): ump = universal.UniversalMediaPlayer(self.hass, **config) - self.assertEqual(None, ump.master_state) + assert ump.master_state is None def test_master_state_with_attrs(self): """Test master state property.""" @@ -316,9 +316,9 @@ class TestMediaPlayer(unittest.TestCase): ump = universal.UniversalMediaPlayer(self.hass, **config) - self.assertEqual(STATE_OFF, ump.master_state) + assert STATE_OFF == ump.master_state self.hass.states.set(self.mock_state_switch_id, STATE_ON) - self.assertEqual(STATE_ON, ump.master_state) + assert STATE_ON == ump.master_state def test_master_state_with_template(self): """Test the state_template option.""" @@ -331,9 +331,9 @@ class TestMediaPlayer(unittest.TestCase): ump = universal.UniversalMediaPlayer(self.hass, **config) - self.assertEqual(STATE_ON, ump.master_state) + assert STATE_ON == ump.master_state self.hass.states.set('input_boolean.test', STATE_ON) - self.assertEqual(STATE_OFF, ump.master_state) + assert STATE_OFF == ump.master_state def test_master_state_with_bad_attrs(self): """Test master state property.""" @@ -343,7 +343,7 @@ class TestMediaPlayer(unittest.TestCase): ump = universal.UniversalMediaPlayer(self.hass, **config) - self.assertEqual(STATE_OFF, ump.master_state) + assert STATE_OFF == ump.master_state def test_active_child_state(self): """Test active child state property.""" @@ -353,28 +353,28 @@ class TestMediaPlayer(unittest.TestCase): ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name']) run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(None, ump._child_state) + assert ump._child_state is None self.mock_mp_1._state = STATE_PLAYING self.mock_mp_1.schedule_update_ha_state() self.hass.block_till_done() run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(self.mock_mp_1.entity_id, - ump._child_state.entity_id) + assert self.mock_mp_1.entity_id == \ + ump._child_state.entity_id self.mock_mp_2._state = STATE_PLAYING self.mock_mp_2.schedule_update_ha_state() self.hass.block_till_done() run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(self.mock_mp_1.entity_id, - ump._child_state.entity_id) + assert self.mock_mp_1.entity_id == \ + ump._child_state.entity_id self.mock_mp_1._state = STATE_OFF self.mock_mp_1.schedule_update_ha_state() self.hass.block_till_done() run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(self.mock_mp_2.entity_id, - ump._child_state.entity_id) + assert self.mock_mp_2.entity_id == \ + ump._child_state.entity_id def test_name(self): """Test name property.""" @@ -382,7 +382,7 @@ class TestMediaPlayer(unittest.TestCase): ump = universal.UniversalMediaPlayer(self.hass, **config) - self.assertEqual(config['name'], ump.name) + assert config['name'] == ump.name def test_polling(self): """Test should_poll property.""" @@ -390,7 +390,7 @@ class TestMediaPlayer(unittest.TestCase): ump = universal.UniversalMediaPlayer(self.hass, **config) - self.assertEqual(False, ump.should_poll) + assert ump.should_poll is False def test_state_children_only(self): """Test media player state with only children.""" @@ -400,13 +400,13 @@ class TestMediaPlayer(unittest.TestCase): ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name']) run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertTrue(ump.state, STATE_OFF) + assert ump.state, STATE_OFF self.mock_mp_1._state = STATE_PLAYING self.mock_mp_1.schedule_update_ha_state() self.hass.block_till_done() run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(STATE_PLAYING, ump.state) + assert STATE_PLAYING == ump.state def test_state_with_children_and_attrs(self): """Test media player with children and master state.""" @@ -416,21 +416,21 @@ class TestMediaPlayer(unittest.TestCase): ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name']) run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(STATE_OFF, ump.state) + assert STATE_OFF == ump.state self.hass.states.set(self.mock_state_switch_id, STATE_ON) run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(STATE_ON, ump.state) + assert STATE_ON == ump.state self.mock_mp_1._state = STATE_PLAYING self.mock_mp_1.schedule_update_ha_state() self.hass.block_till_done() run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(STATE_PLAYING, ump.state) + assert STATE_PLAYING == ump.state self.hass.states.set(self.mock_state_switch_id, STATE_OFF) run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(STATE_OFF, ump.state) + assert STATE_OFF == ump.state def test_volume_level(self): """Test volume level property.""" @@ -440,19 +440,19 @@ class TestMediaPlayer(unittest.TestCase): ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name']) run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(None, ump.volume_level) + assert ump.volume_level is None self.mock_mp_1._state = STATE_PLAYING self.mock_mp_1.schedule_update_ha_state() self.hass.block_till_done() run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(0, ump.volume_level) + assert 0 == ump.volume_level self.mock_mp_1._volume_level = 1 self.mock_mp_1.schedule_update_ha_state() self.hass.block_till_done() run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(1, ump.volume_level) + assert 1 == ump.volume_level def test_media_image_url(self): """Test media_image_url property.""" @@ -463,7 +463,7 @@ class TestMediaPlayer(unittest.TestCase): ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name']) run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(None, ump.media_image_url) + assert ump.media_image_url is None self.mock_mp_1._state = STATE_PLAYING self.mock_mp_1._media_image_url = test_url @@ -472,7 +472,7 @@ class TestMediaPlayer(unittest.TestCase): run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() # mock_mp_1 will convert the url to the api proxy url. This test # ensures ump passes through the same url without an additional proxy. - self.assertEqual(self.mock_mp_1.entity_picture, ump.entity_picture) + assert self.mock_mp_1.entity_picture == ump.entity_picture def test_is_volume_muted_children_only(self): """Test is volume muted property w/ children only.""" @@ -482,19 +482,19 @@ class TestMediaPlayer(unittest.TestCase): ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name']) run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertFalse(ump.is_volume_muted) + assert not ump.is_volume_muted self.mock_mp_1._state = STATE_PLAYING self.mock_mp_1.schedule_update_ha_state() self.hass.block_till_done() run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertFalse(ump.is_volume_muted) + assert not ump.is_volume_muted self.mock_mp_1._is_volume_muted = True self.mock_mp_1.schedule_update_ha_state() self.hass.block_till_done() run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertTrue(ump.is_volume_muted) + assert ump.is_volume_muted def test_source_list_children_and_attr(self): """Test source list property w/ children and attrs.""" @@ -502,10 +502,10 @@ class TestMediaPlayer(unittest.TestCase): ump = universal.UniversalMediaPlayer(self.hass, **config) - self.assertEqual("['dvd', 'htpc']", ump.source_list) + assert "['dvd', 'htpc']" == ump.source_list self.hass.states.set(self.mock_source_list_id, ['dvd', 'htpc', 'game']) - self.assertEqual("['dvd', 'htpc', 'game']", ump.source_list) + assert "['dvd', 'htpc', 'game']" == ump.source_list def test_source_children_and_attr(self): """Test source property w/ children and attrs.""" @@ -513,10 +513,10 @@ class TestMediaPlayer(unittest.TestCase): ump = universal.UniversalMediaPlayer(self.hass, **config) - self.assertEqual('dvd', ump.source) + assert 'dvd' == ump.source self.hass.states.set(self.mock_source_id, 'htpc') - self.assertEqual('htpc', ump.source) + assert 'htpc' == ump.source def test_volume_level_children_and_attr(self): """Test volume level property w/ children and attrs.""" @@ -524,10 +524,10 @@ class TestMediaPlayer(unittest.TestCase): ump = universal.UniversalMediaPlayer(self.hass, **config) - self.assertEqual('0', ump.volume_level) + assert '0' == ump.volume_level self.hass.states.set(self.mock_volume_id, 100) - self.assertEqual('100', ump.volume_level) + assert '100' == ump.volume_level def test_is_volume_muted_children_and_attr(self): """Test is volume muted property w/ children and attrs.""" @@ -535,10 +535,10 @@ class TestMediaPlayer(unittest.TestCase): ump = universal.UniversalMediaPlayer(self.hass, **config) - self.assertFalse(ump.is_volume_muted) + assert not ump.is_volume_muted self.hass.states.set(self.mock_mute_switch_id, STATE_ON) - self.assertTrue(ump.is_volume_muted) + assert ump.is_volume_muted def test_supported_features_children_only(self): """Test supported media commands with only children.""" @@ -548,14 +548,14 @@ class TestMediaPlayer(unittest.TestCase): ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name']) run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(0, ump.supported_features) + assert 0 == ump.supported_features self.mock_mp_1._supported_features = 512 self.mock_mp_1._state = STATE_PLAYING self.mock_mp_1.schedule_update_ha_state() self.hass.block_till_done() run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() - self.assertEqual(512, ump.supported_features) + assert 512 == ump.supported_features def test_supported_features_children_and_cmds(self): """Test supported media commands with children and attrs.""" @@ -586,7 +586,7 @@ class TestMediaPlayer(unittest.TestCase): | universal.SUPPORT_VOLUME_STEP | universal.SUPPORT_VOLUME_MUTE \ | universal.SUPPORT_SELECT_SOURCE | universal.SUPPORT_SHUFFLE_SET - self.assertEqual(check_flags, ump.supported_features) + assert check_flags == ump.supported_features def test_service_call_no_active_child(self): """Test a service call to children with no active child.""" @@ -606,8 +606,8 @@ class TestMediaPlayer(unittest.TestCase): run_coroutine_threadsafe( ump.async_turn_off(), self.hass.loop).result() - self.assertEqual(0, len(self.mock_mp_1.service_calls['turn_off'])) - self.assertEqual(0, len(self.mock_mp_2.service_calls['turn_off'])) + assert 0 == len(self.mock_mp_1.service_calls['turn_off']) + assert 0 == len(self.mock_mp_2.service_calls['turn_off']) def test_service_call_to_child(self): """Test service calls that should be routed to a child.""" @@ -625,88 +625,82 @@ class TestMediaPlayer(unittest.TestCase): run_coroutine_threadsafe( ump.async_turn_off(), self.hass.loop).result() - self.assertEqual(1, len(self.mock_mp_2.service_calls['turn_off'])) + assert 1 == len(self.mock_mp_2.service_calls['turn_off']) run_coroutine_threadsafe( ump.async_turn_on(), self.hass.loop).result() - self.assertEqual(1, len(self.mock_mp_2.service_calls['turn_on'])) + assert 1 == len(self.mock_mp_2.service_calls['turn_on']) run_coroutine_threadsafe( ump.async_mute_volume(True), self.hass.loop).result() - self.assertEqual(1, len(self.mock_mp_2.service_calls['mute_volume'])) + assert 1 == len(self.mock_mp_2.service_calls['mute_volume']) run_coroutine_threadsafe( ump.async_set_volume_level(0.5), self.hass.loop).result() - self.assertEqual( - 1, len(self.mock_mp_2.service_calls['set_volume_level'])) + assert 1 == len(self.mock_mp_2.service_calls['set_volume_level']) run_coroutine_threadsafe( ump.async_media_play(), self.hass.loop).result() - self.assertEqual(1, len(self.mock_mp_2.service_calls['media_play'])) + assert 1 == len(self.mock_mp_2.service_calls['media_play']) run_coroutine_threadsafe( ump.async_media_pause(), self.hass.loop).result() - self.assertEqual(1, len(self.mock_mp_2.service_calls['media_pause'])) + assert 1 == len(self.mock_mp_2.service_calls['media_pause']) run_coroutine_threadsafe( ump.async_media_previous_track(), self.hass.loop).result() - self.assertEqual( - 1, len(self.mock_mp_2.service_calls['media_previous_track'])) + assert 1 == len(self.mock_mp_2.service_calls['media_previous_track']) run_coroutine_threadsafe( ump.async_media_next_track(), self.hass.loop).result() - self.assertEqual( - 1, len(self.mock_mp_2.service_calls['media_next_track'])) + assert 1 == len(self.mock_mp_2.service_calls['media_next_track']) run_coroutine_threadsafe( ump.async_media_seek(100), self.hass.loop).result() - self.assertEqual(1, len(self.mock_mp_2.service_calls['media_seek'])) + assert 1 == len(self.mock_mp_2.service_calls['media_seek']) run_coroutine_threadsafe( ump.async_play_media('movie', 'batman'), self.hass.loop).result() - self.assertEqual(1, len(self.mock_mp_2.service_calls['play_media'])) + assert 1 == len(self.mock_mp_2.service_calls['play_media']) run_coroutine_threadsafe( ump.async_volume_up(), self.hass.loop).result() - self.assertEqual(1, len(self.mock_mp_2.service_calls['volume_up'])) + assert 1 == len(self.mock_mp_2.service_calls['volume_up']) run_coroutine_threadsafe( ump.async_volume_down(), self.hass.loop).result() - self.assertEqual(1, len(self.mock_mp_2.service_calls['volume_down'])) + assert 1 == len(self.mock_mp_2.service_calls['volume_down']) run_coroutine_threadsafe( ump.async_media_play_pause(), self.hass.loop).result() - self.assertEqual( - 1, len(self.mock_mp_2.service_calls['media_play_pause'])) + assert 1 == len(self.mock_mp_2.service_calls['media_play_pause']) run_coroutine_threadsafe( ump.async_select_source('dvd'), self.hass.loop).result() - self.assertEqual( - 1, len(self.mock_mp_2.service_calls['select_source'])) + assert 1 == len(self.mock_mp_2.service_calls['select_source']) run_coroutine_threadsafe( ump.async_clear_playlist(), self.hass.loop).result() - self.assertEqual( - 1, len(self.mock_mp_2.service_calls['clear_playlist'])) + assert 1 == len(self.mock_mp_2.service_calls['clear_playlist']) run_coroutine_threadsafe( ump.async_set_shuffle(True), self.hass.loop).result() - self.assertEqual(1, len(self.mock_mp_2.service_calls['shuffle_set'])) + assert 1 == len(self.mock_mp_2.service_calls['shuffle_set']) def test_service_call_to_command(self): """Test service call to command.""" @@ -727,4 +721,4 @@ class TestMediaPlayer(unittest.TestCase): run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result() run_coroutine_threadsafe(ump.async_turn_off(), self.hass.loop).result() - self.assertEqual(1, len(service)) + assert 1 == len(service) diff --git a/tests/components/media_player/test_yamaha.py b/tests/components/media_player/test_yamaha.py index a55429c0c..13d5a785e 100644 --- a/tests/components/media_player/test_yamaha.py +++ b/tests/components/media_player/test_yamaha.py @@ -67,7 +67,7 @@ class TestYamahaMediaPlayer(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, mp.DOMAIN, config)) + assert setup_component(self.hass, mp.DOMAIN, config) @patch('rxv.RXV') def test_enable_output(self, mock_rxv): diff --git a/tests/components/mqtt/test_discovery.py b/tests/components/mqtt/test_discovery.py index dd3ab2e6f..b075b8db0 100644 --- a/tests/components/mqtt/test_discovery.py +++ b/tests/components/mqtt/test_discovery.py @@ -4,7 +4,7 @@ from unittest.mock import patch from homeassistant.components import mqtt from homeassistant.components.mqtt.discovery import async_start, \ - ALREADY_DISCOVERED + ALREADY_DISCOVERED from homeassistant.const import STATE_ON, STATE_OFF from tests.common import async_fire_mqtt_message, mock_coro, MockConfigEntry diff --git a/tests/components/mqtt/test_init.py b/tests/components/mqtt/test_init.py index 045a411a2..5d7afbde8 100644 --- a/tests/components/mqtt/test_init.py +++ b/tests/components/mqtt/test_init.py @@ -71,7 +71,7 @@ class TestMQTTComponent(unittest.TestCase): """Test if client stops on HA stop.""" self.hass.bus.fire(EVENT_HOMEASSISTANT_STOP) self.hass.block_till_done() - self.assertTrue(self.hass.data['mqtt'].async_disconnect.called) + assert self.hass.data['mqtt'].async_disconnect.called def test_publish_calls_service(self): """Test the publishing of call to services.""" @@ -81,13 +81,11 @@ class TestMQTTComponent(unittest.TestCase): self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual( - 'test-topic', - self.calls[0][0].data['service_data'][mqtt.ATTR_TOPIC]) - self.assertEqual( - 'test-payload', - self.calls[0][0].data['service_data'][mqtt.ATTR_PAYLOAD]) + assert 1 == len(self.calls) + assert 'test-topic' == \ + self.calls[0][0].data['service_data'][mqtt.ATTR_TOPIC] + assert 'test-payload' == \ + self.calls[0][0].data['service_data'][mqtt.ATTR_PAYLOAD] def test_service_call_without_topic_does_not_publish(self): """Test the service call if topic is missing.""" @@ -96,7 +94,7 @@ class TestMQTTComponent(unittest.TestCase): ATTR_SERVICE: mqtt.SERVICE_PUBLISH }) self.hass.block_till_done() - self.assertTrue(not self.hass.data['mqtt'].async_publish.called) + assert not self.hass.data['mqtt'].async_publish.called def test_service_call_with_template_payload_renders_template(self): """Test the service call with rendered template. @@ -105,9 +103,8 @@ class TestMQTTComponent(unittest.TestCase): """ mqtt.publish_template(self.hass, "test/topic", "{{ 1+1 }}") self.hass.block_till_done() - self.assertTrue(self.hass.data['mqtt'].async_publish.called) - self.assertEqual( - self.hass.data['mqtt'].async_publish.call_args[0][1], "2") + assert self.hass.data['mqtt'].async_publish.called + assert self.hass.data['mqtt'].async_publish.call_args[0][1] == "2" def test_service_call_with_payload_doesnt_render_template(self): """Test the service call with unrendered template. @@ -121,7 +118,7 @@ class TestMQTTComponent(unittest.TestCase): mqtt.ATTR_PAYLOAD: payload, mqtt.ATTR_PAYLOAD_TEMPLATE: payload_template }, blocking=True) - self.assertFalse(self.hass.data['mqtt'].async_publish.called) + assert not self.hass.data['mqtt'].async_publish.called def test_service_call_with_ascii_qos_retain_flags(self): """Test the service call with args that can be misinterpreted. @@ -134,22 +131,26 @@ class TestMQTTComponent(unittest.TestCase): mqtt.ATTR_QOS: '2', mqtt.ATTR_RETAIN: 'no' }, blocking=True) - self.assertTrue(self.hass.data['mqtt'].async_publish.called) - self.assertEqual( - self.hass.data['mqtt'].async_publish.call_args[0][2], 2) - self.assertFalse(self.hass.data['mqtt'].async_publish.call_args[0][3]) + assert self.hass.data['mqtt'].async_publish.called + assert self.hass.data['mqtt'].async_publish.call_args[0][2] == 2 + assert not self.hass.data['mqtt'].async_publish.call_args[0][3] def test_validate_topic(self): """Test topic name/filter validation.""" # Invalid UTF-8, must not contain U+D800 to U+DFFF. - self.assertRaises(vol.Invalid, mqtt.valid_topic, '\ud800') - self.assertRaises(vol.Invalid, mqtt.valid_topic, '\udfff') + with pytest.raises(vol.Invalid): + mqtt.valid_topic('\ud800') + with pytest.raises(vol.Invalid): + mqtt.valid_topic('\udfff') # Topic MUST NOT be empty - self.assertRaises(vol.Invalid, mqtt.valid_topic, '') + with pytest.raises(vol.Invalid): + mqtt.valid_topic('') # Topic MUST NOT be longer than 65535 encoded bytes. - self.assertRaises(vol.Invalid, mqtt.valid_topic, 'ü' * 32768) + with pytest.raises(vol.Invalid): + mqtt.valid_topic('ü' * 32768) # UTF-8 MUST NOT include null character - self.assertRaises(vol.Invalid, mqtt.valid_topic, 'bad\0one') + with pytest.raises(vol.Invalid): + mqtt.valid_topic('bad\0one') # Topics "SHOULD NOT" include these special characters # (not MUST NOT, RFC2119). The receiver MAY close the connection. @@ -163,17 +164,25 @@ class TestMQTTComponent(unittest.TestCase): """Test invalid subscribe topics.""" mqtt.valid_subscribe_topic('#') mqtt.valid_subscribe_topic('sport/#') - self.assertRaises(vol.Invalid, mqtt.valid_subscribe_topic, 'sport/#/') - self.assertRaises(vol.Invalid, mqtt.valid_subscribe_topic, 'foo/bar#') - self.assertRaises(vol.Invalid, mqtt.valid_subscribe_topic, 'foo/#/bar') + with pytest.raises(vol.Invalid): + mqtt.valid_subscribe_topic('sport/#/') + with pytest.raises(vol.Invalid): + mqtt.valid_subscribe_topic('foo/bar#') + with pytest.raises(vol.Invalid): + mqtt.valid_subscribe_topic('foo/#/bar') mqtt.valid_subscribe_topic('+') mqtt.valid_subscribe_topic('+/tennis/#') - self.assertRaises(vol.Invalid, mqtt.valid_subscribe_topic, 'sport+') - self.assertRaises(vol.Invalid, mqtt.valid_subscribe_topic, 'sport+/') - self.assertRaises(vol.Invalid, mqtt.valid_subscribe_topic, 'sport/+1') - self.assertRaises(vol.Invalid, mqtt.valid_subscribe_topic, 'sport/+#') - self.assertRaises(vol.Invalid, mqtt.valid_subscribe_topic, 'bad+topic') + with pytest.raises(vol.Invalid): + mqtt.valid_subscribe_topic('sport+') + with pytest.raises(vol.Invalid): + mqtt.valid_subscribe_topic('sport+/') + with pytest.raises(vol.Invalid): + mqtt.valid_subscribe_topic('sport/+1') + with pytest.raises(vol.Invalid): + mqtt.valid_subscribe_topic('sport/+#') + with pytest.raises(vol.Invalid): + mqtt.valid_subscribe_topic('bad+topic') mqtt.valid_subscribe_topic('sport/+/player1') mqtt.valid_subscribe_topic('/finance') mqtt.valid_subscribe_topic('+/+') @@ -181,10 +190,14 @@ class TestMQTTComponent(unittest.TestCase): def test_validate_publish_topic(self): """Test invalid publish topics.""" - self.assertRaises(vol.Invalid, mqtt.valid_publish_topic, 'pub+') - self.assertRaises(vol.Invalid, mqtt.valid_publish_topic, 'pub/+') - self.assertRaises(vol.Invalid, mqtt.valid_publish_topic, '1#') - self.assertRaises(vol.Invalid, mqtt.valid_publish_topic, 'bad+topic') + with pytest.raises(vol.Invalid): + mqtt.valid_publish_topic('pub+') + with pytest.raises(vol.Invalid): + mqtt.valid_publish_topic('pub/+') + with pytest.raises(vol.Invalid): + mqtt.valid_publish_topic('1#') + with pytest.raises(vol.Invalid): + mqtt.valid_publish_topic('bad+topic') mqtt.valid_publish_topic('//') # Topic names beginning with $ SHOULD NOT be used, but can @@ -218,18 +231,20 @@ class TestMQTTComponent(unittest.TestCase): 'sw_version': '0.1-beta', }) # no identifiers - self.assertRaises(vol.Invalid, mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA, { - 'manufacturer': 'Whatever', - 'name': 'Beer', - 'model': 'Glass', - 'sw_version': '0.1-beta', - }) + with pytest.raises(vol.Invalid): + mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA({ + 'manufacturer': 'Whatever', + 'name': 'Beer', + 'model': 'Glass', + 'sw_version': '0.1-beta', + }) # empty identifiers - self.assertRaises(vol.Invalid, mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA, { - 'identifiers': [], - 'connections': [], - 'name': 'Beer', - }) + with pytest.raises(vol.Invalid): + mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA({ + 'identifiers': [], + 'connections': [], + 'name': 'Beer', + }) # pylint: disable=invalid-name @@ -253,7 +268,7 @@ class TestMQTTCallbacks(unittest.TestCase): def aiohttp_client_starts_on_home_assistant_mqtt_setup(self): """Test if client is connected after mqtt init on bootstrap.""" - self.assertEqual(self.hass.data['mqtt']._mqttc.connect.call_count, 1) + assert self.hass.data['mqtt']._mqttc.connect.call_count == 1 def test_receiving_non_utf8_message_gets_logged(self): """Test receiving a non utf8 encoded message.""" @@ -263,10 +278,10 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', b'\x9a') self.hass.block_till_done() - self.assertIn( - "WARNING:homeassistant.components.mqtt:Can't decode payload " - "b'\\x9a' on test-topic with encoding utf-8", - test_handle.output[0]) + assert \ + "WARNING:homeassistant.components.mqtt:Can't decode payload " \ + "b'\\x9a' on test-topic with encoding utf-8" in \ + test_handle.output[0] def test_all_subscriptions_run_when_decode_fails(self): """Test all other subscriptions still run when decode fails for one.""" @@ -277,7 +292,7 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', '°C') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_subscribe_topic(self): """Test the subscription of a topic.""" @@ -286,16 +301,16 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', 'test-payload') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('test-topic', self.calls[0][0]) - self.assertEqual('test-payload', self.calls[0][1]) + assert 1 == len(self.calls) + assert 'test-topic' == self.calls[0][0] + assert 'test-payload' == self.calls[0][1] unsub() fire_mqtt_message(self.hass, 'test-topic', 'test-payload') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) + assert 1 == len(self.calls) def test_subscribe_topic_not_match(self): """Test if subscribed topic is not a match.""" @@ -304,7 +319,7 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'another-test-topic', 'test-payload') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_subscribe_topic_level_wildcard(self): """Test the subscription of wildcard topics.""" @@ -313,9 +328,9 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic/bier/on', 'test-payload') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('test-topic/bier/on', self.calls[0][0]) - self.assertEqual('test-payload', self.calls[0][1]) + assert 1 == len(self.calls) + assert 'test-topic/bier/on' == self.calls[0][0] + assert 'test-payload' == self.calls[0][1] def test_subscribe_topic_level_wildcard_no_subtree_match(self): """Test the subscription of wildcard topics.""" @@ -324,7 +339,7 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic/bier', 'test-payload') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_subscribe_topic_level_wildcard_root_topic_no_subtree_match(self): """Test the subscription of wildcard topics.""" @@ -333,7 +348,7 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic-123', 'test-payload') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_subscribe_topic_subtree_wildcard_subtree_topic(self): """Test the subscription of wildcard topics.""" @@ -342,9 +357,9 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic/bier/on', 'test-payload') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('test-topic/bier/on', self.calls[0][0]) - self.assertEqual('test-payload', self.calls[0][1]) + assert 1 == len(self.calls) + assert 'test-topic/bier/on' == self.calls[0][0] + assert 'test-payload' == self.calls[0][1] def test_subscribe_topic_subtree_wildcard_root_topic(self): """Test the subscription of wildcard topics.""" @@ -353,9 +368,9 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', 'test-payload') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('test-topic', self.calls[0][0]) - self.assertEqual('test-payload', self.calls[0][1]) + assert 1 == len(self.calls) + assert 'test-topic' == self.calls[0][0] + assert 'test-payload' == self.calls[0][1] def test_subscribe_topic_subtree_wildcard_no_match(self): """Test the subscription of wildcard topics.""" @@ -364,7 +379,7 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'another-test-topic', 'test-payload') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_subscribe_topic_level_wildcard_and_wildcard_root_topic(self): """Test the subscription of wildcard topics.""" @@ -373,9 +388,9 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'hi/test-topic', 'test-payload') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('hi/test-topic', self.calls[0][0]) - self.assertEqual('test-payload', self.calls[0][1]) + assert 1 == len(self.calls) + assert 'hi/test-topic' == self.calls[0][0] + assert 'test-payload' == self.calls[0][1] def test_subscribe_topic_level_wildcard_and_wildcard_subtree_topic(self): """Test the subscription of wildcard topics.""" @@ -384,9 +399,9 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'hi/test-topic/here-iam', 'test-payload') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('hi/test-topic/here-iam', self.calls[0][0]) - self.assertEqual('test-payload', self.calls[0][1]) + assert 1 == len(self.calls) + assert 'hi/test-topic/here-iam' == self.calls[0][0] + assert 'test-payload' == self.calls[0][1] def test_subscribe_topic_level_wildcard_and_wildcard_level_no_match(self): """Test the subscription of wildcard topics.""" @@ -395,7 +410,7 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'hi/here-iam/test-topic', 'test-payload') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_subscribe_topic_level_wildcard_and_wildcard_no_match(self): """Test the subscription of wildcard topics.""" @@ -404,7 +419,7 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, 'hi/another-test-topic', 'test-payload') self.hass.block_till_done() - self.assertEqual(0, len(self.calls)) + assert 0 == len(self.calls) def test_subscribe_topic_sys_root(self): """Test the subscription of $ root topics.""" @@ -413,9 +428,9 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, '$test-topic/subtree/on', 'test-payload') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('$test-topic/subtree/on', self.calls[0][0]) - self.assertEqual('test-payload', self.calls[0][1]) + assert 1 == len(self.calls) + assert '$test-topic/subtree/on' == self.calls[0][0] + assert 'test-payload' == self.calls[0][1] def test_subscribe_topic_sys_root_and_wildcard_topic(self): """Test the subscription of $ root and wildcard topics.""" @@ -424,9 +439,9 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, '$test-topic/some-topic', 'test-payload') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('$test-topic/some-topic', self.calls[0][0]) - self.assertEqual('test-payload', self.calls[0][1]) + assert 1 == len(self.calls) + assert '$test-topic/some-topic' == self.calls[0][0] + assert 'test-payload' == self.calls[0][1] def test_subscribe_topic_sys_root_and_wildcard_subtree_topic(self): """Test the subscription of $ root and wildcard subtree topics.""" @@ -436,9 +451,9 @@ class TestMQTTCallbacks(unittest.TestCase): 'test-payload') self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual('$test-topic/subtree/some-topic', self.calls[0][0]) - self.assertEqual('test-payload', self.calls[0][1]) + assert 1 == len(self.calls) + assert '$test-topic/subtree/some-topic' == self.calls[0][0] + assert 'test-payload' == self.calls[0][1] def test_subscribe_special_characters(self): """Test the subscription to topics with special characters.""" @@ -449,9 +464,9 @@ class TestMQTTCallbacks(unittest.TestCase): fire_mqtt_message(self.hass, topic, payload) self.hass.block_till_done() - self.assertEqual(1, len(self.calls)) - self.assertEqual(topic, self.calls[0][0]) - self.assertEqual(payload, self.calls[0][1]) + assert 1 == len(self.calls) + assert topic == self.calls[0][0] + assert payload == self.calls[0][1] def test_mqtt_failed_connection_results_in_disconnect(self): """Test if connection failure leads to disconnect.""" @@ -459,12 +474,12 @@ class TestMQTTCallbacks(unittest.TestCase): self.hass.data['mqtt']._mqttc = mock.MagicMock() self.hass.data['mqtt']._mqtt_on_connect( None, {'topics': {}}, 0, result_code) - self.assertTrue(self.hass.data['mqtt']._mqttc.disconnect.called) + assert self.hass.data['mqtt']._mqttc.disconnect.called def test_mqtt_disconnect_tries_no_reconnect_on_stop(self): """Test the disconnect tries.""" self.hass.data['mqtt']._mqtt_on_disconnect(None, None, 0) - self.assertFalse(self.hass.data['mqtt']._mqttc.reconnect.called) + assert not self.hass.data['mqtt']._mqttc.reconnect.called @mock.patch('homeassistant.components.mqtt.time.sleep') def test_mqtt_disconnect_tries_reconnect(self, mock_sleep): @@ -476,11 +491,10 @@ class TestMQTTCallbacks(unittest.TestCase): ] self.hass.data['mqtt']._mqttc.reconnect.side_effect = [1, 1, 1, 0] self.hass.data['mqtt']._mqtt_on_disconnect(None, None, 1) - self.assertTrue(self.hass.data['mqtt']._mqttc.reconnect.called) - self.assertEqual( - 4, len(self.hass.data['mqtt']._mqttc.reconnect.mock_calls)) - self.assertEqual([1, 2, 4], - [call[1][0] for call in mock_sleep.mock_calls]) + assert self.hass.data['mqtt']._mqttc.reconnect.called + assert 4 == len(self.hass.data['mqtt']._mqttc.reconnect.mock_calls) + assert [1, 2, 4] == \ + [call[1][0] for call in mock_sleep.mock_calls] def test_retained_message_on_subscribe_received(self): """Test every subscriber receives retained message on subscribe.""" @@ -493,34 +507,34 @@ class TestMQTTCallbacks(unittest.TestCase): calls_a = mock.MagicMock() mqtt.subscribe(self.hass, 'test/state', calls_a) self.hass.block_till_done() - self.assertTrue(calls_a.called) + assert calls_a.called calls_b = mock.MagicMock() mqtt.subscribe(self.hass, 'test/state', calls_b) self.hass.block_till_done() - self.assertTrue(calls_b.called) + assert calls_b.called def test_not_calling_unsubscribe_with_active_subscribers(self): """Test not calling unsubscribe() when other subscribers are active.""" unsub = mqtt.subscribe(self.hass, 'test/state', None) mqtt.subscribe(self.hass, 'test/state', None) self.hass.block_till_done() - self.assertTrue(self.hass.data['mqtt']._mqttc.subscribe.called) + assert self.hass.data['mqtt']._mqttc.subscribe.called unsub() self.hass.block_till_done() - self.assertFalse(self.hass.data['mqtt']._mqttc.unsubscribe.called) + assert not self.hass.data['mqtt']._mqttc.unsubscribe.called def test_restore_subscriptions_on_reconnect(self): """Test subscriptions are restored on reconnect.""" mqtt.subscribe(self.hass, 'test/state', None) self.hass.block_till_done() - self.assertEqual(self.hass.data['mqtt']._mqttc.subscribe.call_count, 1) + assert self.hass.data['mqtt']._mqttc.subscribe.call_count == 1 self.hass.data['mqtt']._mqtt_on_disconnect(None, None, 0) self.hass.data['mqtt']._mqtt_on_connect(None, None, None, 0) self.hass.block_till_done() - self.assertEqual(self.hass.data['mqtt']._mqttc.subscribe.call_count, 2) + assert self.hass.data['mqtt']._mqttc.subscribe.call_count == 2 def test_restore_all_active_subscriptions_on_reconnect(self): """Test active subscriptions are restored correctly on reconnect.""" @@ -538,21 +552,21 @@ class TestMQTTCallbacks(unittest.TestCase): mock.call('test/state', 0), mock.call('test/state', 1) ] - self.assertEqual(self.hass.data['mqtt']._mqttc.subscribe.mock_calls, - expected) + assert self.hass.data['mqtt']._mqttc.subscribe.mock_calls == \ + expected unsub() self.hass.block_till_done() - self.assertEqual(self.hass.data['mqtt']._mqttc.unsubscribe.call_count, - 0) + assert self.hass.data['mqtt']._mqttc.unsubscribe.call_count == \ + 0 self.hass.data['mqtt']._mqtt_on_disconnect(None, None, 0) self.hass.data['mqtt']._mqtt_on_connect(None, None, None, 0) self.hass.block_till_done() expected.append(mock.call('test/state', 1)) - self.assertEqual(self.hass.data['mqtt']._mqttc.subscribe.mock_calls, - expected) + assert self.hass.data['mqtt']._mqttc.subscribe.mock_calls == \ + expected @asyncio.coroutine diff --git a/tests/components/notify/test_apns.py b/tests/components/notify/test_apns.py index dc120dc4f..9964a58cd 100644 --- a/tests/components/notify/test_apns.py +++ b/tests/components/notify/test_apns.py @@ -120,11 +120,10 @@ class TestApns(unittest.TestCase): Mock(return_value=yaml_file)): self._setup_notify() - self.assertTrue(self.hass.services.call(notify.DOMAIN, - 'apns_test_app', - {'push_id': '1234', - 'name': 'test device'}, - blocking=True)) + assert self.hass.services.call(notify.DOMAIN, 'apns_test_app', { + 'push_id': '1234', + 'name': 'test device' + }, blocking=True) assert len(written_devices) == 1 assert written_devices[0].name == 'test device' @@ -156,16 +155,16 @@ class TestApns(unittest.TestCase): Mock(return_value=yaml_file)): self._setup_notify() - self.assertTrue(self.hass.services.call(notify.DOMAIN, 'apns_test_app', - {'push_id': '1234'}, - blocking=True)) + assert self.hass.services.call(notify.DOMAIN, 'apns_test_app', { + 'push_id': '1234' + }, blocking=True) devices = {dev.push_id: dev for dev in written_devices} test_device = devices.get('1234') - self.assertIsNotNone(test_device) - self.assertIsNone(test_device.name) + assert test_device is not None + assert test_device.name is None @patch('homeassistant.components.notify.apns._write_device') def test_update_existing_device(self, mock_write): @@ -192,21 +191,20 @@ class TestApns(unittest.TestCase): Mock(return_value=yaml_file)): self._setup_notify() - self.assertTrue(self.hass.services.call(notify.DOMAIN, - 'apns_test_app', - {'push_id': '1234', - 'name': 'updated device 1'}, - blocking=True)) + assert self.hass.services.call(notify.DOMAIN, 'apns_test_app', { + 'push_id': '1234', + 'name': 'updated device 1' + }, blocking=True) devices = {dev.push_id: dev for dev in written_devices} test_device_1 = devices.get('1234') test_device_2 = devices.get('5678') - self.assertIsNotNone(test_device_1) - self.assertIsNotNone(test_device_2) + assert test_device_1 is not None + assert test_device_2 is not None - self.assertEqual('updated device 1', test_device_1.name) + assert 'updated device 1' == test_device_1.name @patch('homeassistant.components.notify.apns._write_device') def test_update_existing_device_with_tracking_id(self, mock_write): @@ -235,24 +233,23 @@ class TestApns(unittest.TestCase): Mock(return_value=yaml_file)): self._setup_notify() - self.assertTrue(self.hass.services.call(notify.DOMAIN, - 'apns_test_app', - {'push_id': '1234', - 'name': 'updated device 1'}, - blocking=True)) + assert self.hass.services.call(notify.DOMAIN, 'apns_test_app', { + 'push_id': '1234', + 'name': 'updated device 1' + }, blocking=True) devices = {dev.push_id: dev for dev in written_devices} test_device_1 = devices.get('1234') test_device_2 = devices.get('5678') - self.assertIsNotNone(test_device_1) - self.assertIsNotNone(test_device_2) + assert test_device_1 is not None + assert test_device_2 is not None - self.assertEqual('tracking123', - test_device_1.tracking_device_id) - self.assertEqual('tracking456', - test_device_2.tracking_device_id) + assert 'tracking123' == \ + test_device_1.tracking_device_id + assert 'tracking456' == \ + test_device_2.tracking_device_id @patch('apns2.client.APNsClient') def test_send(self, mock_client): @@ -266,25 +263,25 @@ class TestApns(unittest.TestCase): Mock(return_value=yaml_file)): self._setup_notify() - self.assertTrue(self.hass.services.call( + assert self.hass.services.call( 'notify', 'test_app', {'message': 'Hello', 'data': { 'badge': 1, 'sound': 'test.mp3', 'category': 'testing'}}, - blocking=True)) + blocking=True) - self.assertTrue(send.called) - self.assertEqual(1, len(send.mock_calls)) + assert send.called + assert 1 == len(send.mock_calls) target = send.mock_calls[0][1][0] payload = send.mock_calls[0][1][1] - self.assertEqual('1234', target) - self.assertEqual('Hello', payload.alert) - self.assertEqual(1, payload.badge) - self.assertEqual('test.mp3', payload.sound) - self.assertEqual('testing', payload.category) + assert '1234' == target + assert 'Hello' == payload.alert + assert 1 == payload.badge + assert 'test.mp3' == payload.sound + assert 'testing' == payload.category @patch('apns2.client.APNsClient') def test_send_when_disabled(self, mock_client): @@ -301,15 +298,15 @@ class TestApns(unittest.TestCase): Mock(return_value=yaml_file)): self._setup_notify() - self.assertTrue(self.hass.services.call( + assert self.hass.services.call( 'notify', 'test_app', {'message': 'Hello', 'data': { 'badge': 1, 'sound': 'test.mp3', 'category': 'testing'}}, - blocking=True)) + blocking=True) - self.assertFalse(send.called) + assert not send.called @patch('apns2.client.APNsClient') def test_send_with_state(self, mock_client): @@ -346,14 +343,14 @@ class TestApns(unittest.TestCase): notify_service.send_message(message='Hello', target='home') - self.assertTrue(send.called) - self.assertEqual(1, len(send.mock_calls)) + assert send.called + assert 1 == len(send.mock_calls) target = send.mock_calls[0][1][0] payload = send.mock_calls[0][1][1] - self.assertEqual('5678', target) - self.assertEqual('Hello', payload.alert) + assert '5678' == target + assert 'Hello' == payload.alert @patch('apns2.client.APNsClient') @patch('homeassistant.components.notify.apns._write_device') @@ -386,15 +383,15 @@ class TestApns(unittest.TestCase): Mock(return_value=yaml_file)): self._setup_notify() - self.assertTrue(self.hass.services.call('notify', 'test_app', - {'message': 'Hello'}, - blocking=True)) + assert self.hass.services.call('notify', 'test_app', + {'message': 'Hello'}, + blocking=True) devices = {dev.push_id: dev for dev in written_devices} test_device_1 = devices.get('1234') - self.assertIsNotNone(test_device_1) - self.assertEqual(True, test_device_1.disabled) + assert test_device_1 is not None + assert test_device_1.disabled is True def test_write_device(): diff --git a/tests/components/notify/test_command_line.py b/tests/components/notify/test_command_line.py index 57933063b..66aa451d3 100644 --- a/tests/components/notify/test_command_line.py +++ b/tests/components/notify/test_command_line.py @@ -49,39 +49,35 @@ class TestCommandLine(unittest.TestCase): filename = os.path.join(tempdirname, 'message.txt') message = 'one, two, testing, testing' with assert_setup_component(1) as handle_config: - self.assertTrue(setup_component(self.hass, notify.DOMAIN, { + assert setup_component(self.hass, notify.DOMAIN, { 'notify': { 'name': 'test', 'platform': 'command_line', 'command': 'echo $(cat) > {}'.format(filename) } - })) + }) assert handle_config[notify.DOMAIN] - self.assertTrue( - self.hass.services.call('notify', 'test', {'message': message}, - blocking=True) - ) + assert self.hass.services.call( + 'notify', 'test', {'message': message}, blocking=True) with open(filename) as fil: # the echo command adds a line break - self.assertEqual(fil.read(), "{}\n".format(message)) + assert fil.read() == "{}\n".format(message) @patch('homeassistant.components.notify.command_line._LOGGER.error') def test_error_for_none_zero_exit_code(self, mock_error): """Test if an error is logged for non zero exit codes.""" with assert_setup_component(1) as handle_config: - self.assertTrue(setup_component(self.hass, notify.DOMAIN, { + assert setup_component(self.hass, notify.DOMAIN, { 'notify': { 'name': 'test', 'platform': 'command_line', 'command': 'echo $(cat); exit 1' } - })) + }) assert handle_config[notify.DOMAIN] - self.assertTrue( - self.hass.services.call('notify', 'test', {'message': 'error'}, - blocking=True) - ) - self.assertEqual(1, mock_error.call_count) + assert self.hass.services.call('notify', 'test', {'message': 'error'}, + blocking=True) + assert 1 == mock_error.call_count diff --git a/tests/components/notify/test_demo.py b/tests/components/notify/test_demo.py index 3be2ddcb8..270736d1b 100644 --- a/tests/components/notify/test_demo.py +++ b/tests/components/notify/test_demo.py @@ -56,10 +56,9 @@ class TestNotifyDemo(unittest.TestCase): self._setup_notify() self.hass.block_till_done() assert mock_demo_get_service.called - self.assertEqual( - log_handle.output, + assert log_handle.output == \ ['ERROR:homeassistant.components.notify:' - 'Failed to initialize notification service demo']) + 'Failed to initialize notification service demo'] @patch('homeassistant.components.notify.demo.get_service', autospec=True) def test_discover_notify(self, mock_demo_get_service): @@ -83,7 +82,7 @@ class TestNotifyDemo(unittest.TestCase): self._setup_notify() common.send_message(self.hass, None) self.hass.block_till_done() - self.assertTrue(len(self.events) == 0) + assert len(self.events) == 0 def test_sending_templated_message(self): """Send a templated message.""" @@ -93,8 +92,8 @@ class TestNotifyDemo(unittest.TestCase): '{{ states.sensor.temperature.name }}') self.hass.block_till_done() last_event = self.events[-1] - self.assertEqual(last_event.data[notify.ATTR_TITLE], 'temperature') - self.assertEqual(last_event.data[notify.ATTR_MESSAGE], '10') + assert last_event.data[notify.ATTR_TITLE] == 'temperature' + assert last_event.data[notify.ATTR_MESSAGE] == '10' def test_method_forwards_correct_data(self): """Test that all data from the service gets forwarded to service.""" @@ -102,7 +101,7 @@ class TestNotifyDemo(unittest.TestCase): common.send_message(self.hass, 'my message', 'my title', {'hello': 'world'}) self.hass.block_till_done() - self.assertTrue(len(self.events) == 1) + assert len(self.events) == 1 data = self.events[0].data assert { 'message': 'my message', @@ -128,7 +127,7 @@ class TestNotifyDemo(unittest.TestCase): script.call_from_config(self.hass, conf) self.hass.block_till_done() - self.assertTrue(len(self.events) == 1) + assert len(self.events) == 1 assert { 'message': 'Test 123 4', 'data': { @@ -158,7 +157,7 @@ class TestNotifyDemo(unittest.TestCase): script.call_from_config(self.hass, conf) self.hass.block_till_done() - self.assertTrue(len(self.events) == 1) + assert len(self.events) == 1 assert { 'message': 'Test 123 4', 'title': 'Test', @@ -171,9 +170,9 @@ class TestNotifyDemo(unittest.TestCase): def test_targets_are_services(self): """Test that all targets are exposed as individual services.""" self._setup_notify() - self.assertIsNotNone(self.hass.services.has_service("notify", "demo")) + assert self.hass.services.has_service("notify", "demo") is not None service = "demo_test_target_name" - self.assertIsNotNone(self.hass.services.has_service("notify", service)) + assert self.hass.services.has_service("notify", service) is not None def test_messages_to_targets_route(self): """Test message routing to specific target services.""" diff --git a/tests/components/notify/test_facebook.py b/tests/components/notify/test_facebook.py index b94a4c38a..a74395d5a 100644 --- a/tests/components/notify/test_facebook.py +++ b/tests/components/notify/test_facebook.py @@ -26,17 +26,17 @@ class TestFacebook(unittest.TestCase): target = ["+15555551234"] self.facebook.send_message(message=message, target=target) - self.assertTrue(mock.called) - self.assertEqual(mock.call_count, 1) + assert mock.called + assert mock.call_count == 1 expected_body = { "recipient": {"phone_number": target[0]}, "message": {"text": message} } - self.assertEqual(mock.last_request.json(), expected_body) + assert mock.last_request.json() == expected_body expected_params = {"access_token": ["page-access-token"]} - self.assertEqual(mock.last_request.qs, expected_params) + assert mock.last_request.qs == expected_params @requests_mock.Mocker() def test_sending_multiple_messages(self, mock): @@ -51,8 +51,8 @@ class TestFacebook(unittest.TestCase): targets = ["+15555551234", "+15555551235"] self.facebook.send_message(message=message, target=targets) - self.assertTrue(mock.called) - self.assertEqual(mock.call_count, 2) + assert mock.called + assert mock.call_count == 2 for idx, target in enumerate(targets): request = mock.request_history[idx] @@ -60,10 +60,10 @@ class TestFacebook(unittest.TestCase): "recipient": {"phone_number": target}, "message": {"text": message} } - self.assertEqual(request.json(), expected_body) + assert request.json() == expected_body expected_params = {"access_token": ["page-access-token"]} - self.assertEqual(request.qs, expected_params) + assert request.qs == expected_params @requests_mock.Mocker() def test_send_message_attachment(self, mock): @@ -84,17 +84,17 @@ class TestFacebook(unittest.TestCase): target = ["+15555551234"] self.facebook.send_message(message=message, data=data, target=target) - self.assertTrue(mock.called) - self.assertEqual(mock.call_count, 1) + assert mock.called + assert mock.call_count == 1 expected_body = { "recipient": {"phone_number": target[0]}, "message": data } - self.assertEqual(mock.last_request.json(), expected_body) + assert mock.last_request.json() == expected_body expected_params = {"access_token": ["page-access-token"]} - self.assertEqual(mock.last_request.qs, expected_params) + assert mock.last_request.qs == expected_params @requests_mock.Mocker() def test_send_targetless_message(self, mock): @@ -106,7 +106,7 @@ class TestFacebook(unittest.TestCase): ) self.facebook.send_message(message="goin nowhere") - self.assertFalse(mock.called) + assert not mock.called @requests_mock.Mocker() def test_send_message_with_400(self, mock): @@ -125,5 +125,5 @@ class TestFacebook(unittest.TestCase): } ) self.facebook.send_message(message="nope!", target=["+15555551234"]) - self.assertTrue(mock.called) - self.assertEqual(mock.call_count, 1) + assert mock.called + assert mock.call_count == 1 diff --git a/tests/components/notify/test_file.py b/tests/components/notify/test_file.py index fb4ab42e9..e67ed5326 100644 --- a/tests/components/notify/test_file.py +++ b/tests/components/notify/test_file.py @@ -40,14 +40,14 @@ class TestNotifyFile(unittest.TestCase): filename = 'mock_file' message = 'one, two, testing, testing' with assert_setup_component(1) as handle_config: - self.assertTrue(setup_component(self.hass, notify.DOMAIN, { + assert setup_component(self.hass, notify.DOMAIN, { 'notify': { 'name': 'test', 'platform': 'file', 'filename': filename, 'timestamp': timestamp, } - })) + }) assert handle_config[notify.DOMAIN] m_open = mock_open() @@ -68,21 +68,17 @@ class TestNotifyFile(unittest.TestCase): blocking=True) full_filename = os.path.join(self.hass.config.path(), filename) - self.assertEqual(m_open.call_count, 1) - self.assertEqual(m_open.call_args, call(full_filename, 'a')) + assert m_open.call_count == 1 + assert m_open.call_args == call(full_filename, 'a') - self.assertEqual(m_open.return_value.write.call_count, 2) + assert m_open.return_value.write.call_count == 2 if not timestamp: - self.assertEqual( - m_open.return_value.write.call_args_list, + assert m_open.return_value.write.call_args_list == \ [call(title), call('{}\n'.format(message))] - ) else: - self.assertEqual( - m_open.return_value.write.call_args_list, + assert m_open.return_value.write.call_args_list == \ [call(title), call('{} {}\n'.format( dt_util.utcnow().isoformat(), message))] - ) def test_notify_file(self): """Test the notify file output without timestamp.""" diff --git a/tests/components/notify/test_pushbullet.py b/tests/components/notify/test_pushbullet.py index 73b9aa4fb..a936a11aa 100644 --- a/tests/components/notify/test_pushbullet.py +++ b/tests/components/notify/test_pushbullet.py @@ -68,13 +68,13 @@ class TestPushBullet(unittest.TestCase): 'message': 'Test Message'} self.hass.services.call(notify.DOMAIN, 'test', data) self.hass.block_till_done() - self.assertTrue(mock.called) - self.assertEqual(mock.call_count, 1) + assert mock.called + assert mock.call_count == 1 expected_body = {'body': 'Test Message', 'title': 'Test Title', 'type': 'note'} - self.assertEqual(mock.last_request.json(), expected_body) + assert mock.last_request.json() == expected_body @requests_mock.Mocker() @patch.object(PushBullet, '_get_data', @@ -99,14 +99,14 @@ class TestPushBullet(unittest.TestCase): 'target': ['device/DESKTOP']} self.hass.services.call(notify.DOMAIN, 'test', data) self.hass.block_till_done() - self.assertTrue(mock.called) - self.assertEqual(mock.call_count, 1) + assert mock.called + assert mock.call_count == 1 expected_body = {'body': 'Test Message', 'device_iden': 'identity1', 'title': 'Test Title', 'type': 'note'} - self.assertEqual(mock.last_request.json(), expected_body) + assert mock.last_request.json() == expected_body @requests_mock.Mocker() @patch.object(PushBullet, '_get_data', @@ -131,20 +131,20 @@ class TestPushBullet(unittest.TestCase): 'target': ['device/DESKTOP', 'device/My iPhone']} self.hass.services.call(notify.DOMAIN, 'test', data) self.hass.block_till_done() - self.assertTrue(mock.called) - self.assertEqual(mock.call_count, 2) - self.assertEqual(len(mock.request_history), 2) + assert mock.called + assert mock.call_count == 2 + assert len(mock.request_history) == 2 expected_body = {'body': 'Test Message', 'device_iden': 'identity1', 'title': 'Test Title', 'type': 'note'} - self.assertEqual(mock.request_history[0].json(), expected_body) + assert mock.request_history[0].json() == expected_body expected_body = {'body': 'Test Message', 'device_iden': 'identity2', 'title': 'Test Title', 'type': 'note'} - self.assertEqual(mock.request_history[1].json(), expected_body) + assert mock.request_history[1].json() == expected_body @requests_mock.Mocker() @patch.object(PushBullet, '_get_data', @@ -169,15 +169,15 @@ class TestPushBullet(unittest.TestCase): 'target': ['email/user@host.net']} self.hass.services.call(notify.DOMAIN, 'test', data) self.hass.block_till_done() - self.assertTrue(mock.called) - self.assertEqual(mock.call_count, 1) - self.assertEqual(len(mock.request_history), 1) + assert mock.called + assert mock.call_count == 1 + assert len(mock.request_history) == 1 expected_body = {'body': 'Test Message', 'email': 'user@host.net', 'title': 'Test Title', 'type': 'note'} - self.assertEqual(mock.request_history[0].json(), expected_body) + assert mock.request_history[0].json() == expected_body @requests_mock.Mocker() @patch.object(PushBullet, '_get_data', @@ -202,20 +202,20 @@ class TestPushBullet(unittest.TestCase): 'target': ['device/DESKTOP', 'email/user@host.net']} self.hass.services.call(notify.DOMAIN, 'test', data) self.hass.block_till_done() - self.assertTrue(mock.called) - self.assertEqual(mock.call_count, 2) - self.assertEqual(len(mock.request_history), 2) + assert mock.called + assert mock.call_count == 2 + assert len(mock.request_history) == 2 expected_body = {'body': 'Test Message', 'device_iden': 'identity1', 'title': 'Test Title', 'type': 'note'} - self.assertEqual(mock.request_history[0].json(), expected_body) + assert mock.request_history[0].json() == expected_body expected_body = {'body': 'Test Message', 'email': 'user@host.net', 'title': 'Test Title', 'type': 'note'} - self.assertEqual(mock.request_history[1].json(), expected_body) + assert mock.request_history[1].json() == expected_body @requests_mock.Mocker() @patch.object(PushBullet, '_get_data', diff --git a/tests/components/notify/test_smtp.py b/tests/components/notify/test_smtp.py index fca0e3c79..fa6c50032 100644 --- a/tests/components/notify/test_smtp.py +++ b/tests/components/notify/test_smtp.py @@ -5,6 +5,7 @@ from unittest.mock import patch from homeassistant.components.notify import smtp from tests.common import get_test_home_assistant +import re class MockSMTP(smtp.MailNotificationService): @@ -45,14 +46,14 @@ class TestNotifySmtp(unittest.TestCase): 'Message-Id: <[^@]+@[^>]+>\n' '\n' 'Test msg$') - self.assertRegex(msg, expected) + assert re.search(expected, msg) @patch('email.utils.make_msgid', return_value='') def test_mixed_email(self, mock_make_msgid): """Test build of mixed text email behavior.""" msg = self.mailer.send_message('Test msg', data={'images': ['test.jpg']}) - self.assertTrue('Content-Type: multipart/related' in msg) + assert 'Content-Type: multipart/related' in msg @patch('email.utils.make_msgid', return_value='') def test_html_email(self, mock_make_msgid): @@ -73,4 +74,4 @@ class TestNotifySmtp(unittest.TestCase): msg = self.mailer.send_message('Test msg', data={'html': html, 'images': ['test.jpg']}) - self.assertTrue('Content-Type: multipart/related' in msg) + assert 'Content-Type: multipart/related' in msg diff --git a/tests/components/recorder/test_purge.py b/tests/components/recorder/test_purge.py index f33236f0c..4249a8abf 100644 --- a/tests/components/recorder/test_purge.py +++ b/tests/components/recorder/test_purge.py @@ -124,13 +124,13 @@ class TestRecorderPurge(unittest.TestCase): # make sure we start with 7 states with session_scope(hass=self.hass) as session: states = session.query(States) - self.assertEqual(states.count(), 7) + assert states.count() == 7 # run purge_old_data() purge_old_data(self.hass.data[DATA_INSTANCE], 4, repack=False) # we should only have 3 states left after purging - self.assertEqual(states.count(), 3) + assert states.count() == 3 def test_purge_old_events(self): """Test deleting old events.""" @@ -139,13 +139,13 @@ class TestRecorderPurge(unittest.TestCase): with session_scope(hass=self.hass) as session: events = session.query(Events).filter( Events.event_type.like("EVENT_TEST%")) - self.assertEqual(events.count(), 7) + assert events.count() == 7 # run purge_old_data() purge_old_data(self.hass.data[DATA_INSTANCE], 4, repack=False) # no state to protect, now we should only have 2 events left - self.assertEqual(events.count(), 2) + assert events.count() == 2 def test_purge_method(self): """Test purge method.""" @@ -156,11 +156,11 @@ class TestRecorderPurge(unittest.TestCase): # make sure we start with 6 states with session_scope(hass=self.hass) as session: states = session.query(States) - self.assertEqual(states.count(), 7) + assert states.count() == 7 events = session.query(Events).filter( Events.event_type.like("EVENT_TEST%")) - self.assertEqual(events.count(), 7) + assert events.count() == 7 self.hass.data[DATA_INSTANCE].block_till_done() @@ -172,8 +172,8 @@ class TestRecorderPurge(unittest.TestCase): self.hass.data[DATA_INSTANCE].block_till_done() # only purged old events - self.assertEqual(states.count(), 5) - self.assertEqual(events.count(), 5) + assert states.count() == 5 + assert events.count() == 5 # run purge method - correct service data self.hass.services.call('recorder', 'purge', @@ -184,19 +184,19 @@ class TestRecorderPurge(unittest.TestCase): self.hass.data[DATA_INSTANCE].block_till_done() # we should only have 3 states left after purging - self.assertEqual(states.count(), 3) + assert states.count() == 3 # the protected state is among them - self.assertTrue('iamprotected' in ( - state.state for state in states)) + assert 'iamprotected' in ( + state.state for state in states) # now we should only have 3 events left - self.assertEqual(events.count(), 3) + assert events.count() == 3 # and the protected event is among them - self.assertTrue('EVENT_TEST_FOR_PROTECTED' in ( - event.event_type for event in events.all())) - self.assertFalse('EVENT_TEST_PURGE' in ( + assert 'EVENT_TEST_FOR_PROTECTED' in ( + event.event_type for event in events.all()) + assert not ('EVENT_TEST_PURGE' in ( event.event_type for event in events.all())) # run purge method - correct service data, with repack @@ -207,5 +207,5 @@ class TestRecorderPurge(unittest.TestCase): service_data=service_data) self.hass.block_till_done() self.hass.data[DATA_INSTANCE].block_till_done() - self.assertEqual(mock_logger.debug.mock_calls[4][1][0], - "Vacuuming SQLite to free space") + assert mock_logger.debug.mock_calls[4][1][0] == \ + "Vacuuming SQLite to free space" diff --git a/tests/components/remote/test_demo.py b/tests/components/remote/test_demo.py index fbf7230c2..c68e34ddc 100644 --- a/tests/components/remote/test_demo.py +++ b/tests/components/remote/test_demo.py @@ -19,9 +19,9 @@ class TestDemoRemote(unittest.TestCase): def setUp(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() - self.assertTrue(setup_component(self.hass, remote.DOMAIN, {'remote': { + assert setup_component(self.hass, remote.DOMAIN, {'remote': { 'platform': 'demo', - }})) + }}) # pylint: disable=invalid-name def tearDown(self): @@ -33,21 +33,20 @@ class TestDemoRemote(unittest.TestCase): common.turn_on(self.hass, entity_id=ENTITY_ID) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ID) - self.assertEqual(state.state, STATE_ON) + assert state.state == STATE_ON common.turn_off(self.hass, entity_id=ENTITY_ID) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ID) - self.assertEqual(state.state, STATE_OFF) + assert state.state == STATE_OFF common.turn_on(self.hass, entity_id=ENTITY_ID) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ID) - self.assertEqual(state.state, STATE_ON) + assert state.state == STATE_ON common.send_command(self.hass, 'test', entity_id=ENTITY_ID) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ID) - self.assertEqual( - state.attributes, - {'friendly_name': 'Remote One', 'last_command_sent': 'test'}) + assert state.attributes == \ + {'friendly_name': 'Remote One', 'last_command_sent': 'test'} diff --git a/tests/components/remote/test_init.py b/tests/components/remote/test_init.py index 21a083e3b..2315dc1cf 100644 --- a/tests/components/remote/test_init.py +++ b/tests/components/remote/test_init.py @@ -3,7 +3,6 @@ import unittest -from homeassistant.setup import setup_component from homeassistant.const import ( ATTR_ENTITY_ID, STATE_ON, STATE_OFF, CONF_PLATFORM, SERVICE_TURN_ON, SERVICE_TURN_OFF) @@ -32,16 +31,16 @@ class TestRemote(unittest.TestCase): def test_is_on(self): """Test is_on.""" self.hass.states.set('remote.test', STATE_ON) - self.assertTrue(remote.is_on(self.hass, 'remote.test')) + assert remote.is_on(self.hass, 'remote.test') self.hass.states.set('remote.test', STATE_OFF) - self.assertFalse(remote.is_on(self.hass, 'remote.test')) + assert not remote.is_on(self.hass, 'remote.test') self.hass.states.set(remote.ENTITY_ID_ALL_REMOTES, STATE_ON) - self.assertTrue(remote.is_on(self.hass)) + assert remote.is_on(self.hass) self.hass.states.set(remote.ENTITY_ID_ALL_REMOTES, STATE_OFF) - self.assertFalse(remote.is_on(self.hass)) + assert not remote.is_on(self.hass) def test_turn_on(self): """Test turn_on.""" @@ -54,10 +53,10 @@ class TestRemote(unittest.TestCase): self.hass.block_till_done() - self.assertEqual(1, len(turn_on_calls)) + assert 1 == len(turn_on_calls) call = turn_on_calls[-1] - self.assertEqual(remote.DOMAIN, call.domain) + assert remote.DOMAIN == call.domain def test_turn_off(self): """Test turn_off.""" @@ -69,12 +68,12 @@ class TestRemote(unittest.TestCase): self.hass.block_till_done() - self.assertEqual(1, len(turn_off_calls)) + assert 1 == len(turn_off_calls) call = turn_off_calls[-1] - self.assertEqual(remote.DOMAIN, call.domain) - self.assertEqual(SERVICE_TURN_OFF, call.service) - self.assertEqual('entity_id_val', call.data[ATTR_ENTITY_ID]) + assert remote.DOMAIN == call.domain + assert SERVICE_TURN_OFF == call.service + assert 'entity_id_val' == call.data[ATTR_ENTITY_ID] def test_send_command(self): """Test send_command.""" @@ -88,14 +87,9 @@ class TestRemote(unittest.TestCase): self.hass.block_till_done() - self.assertEqual(1, len(send_command_calls)) + assert 1 == len(send_command_calls) call = send_command_calls[-1] - self.assertEqual(remote.DOMAIN, call.domain) - self.assertEqual(SERVICE_SEND_COMMAND, call.service) - self.assertEqual('entity_id_val', call.data[ATTR_ENTITY_ID]) - - def test_services(self): - """Test the provided services.""" - self.assertTrue(setup_component(self.hass, remote.DOMAIN, - TEST_PLATFORM)) + assert remote.DOMAIN == call.domain + assert SERVICE_SEND_COMMAND == call.service + assert 'entity_id_val' == call.data[ATTR_ENTITY_ID] diff --git a/tests/components/scene/test_init.py b/tests/components/scene/test_init.py index 81ab5f89c..df96b19f3 100644 --- a/tests/components/scene/test_init.py +++ b/tests/components/scene/test_init.py @@ -21,9 +21,9 @@ class TestScene(unittest.TestCase): test_light = loader.get_component(self.hass, 'light.test') test_light.init() - self.assertTrue(setup_component(self.hass, light.DOMAIN, { + assert setup_component(self.hass, light.DOMAIN, { light.DOMAIN: {'platform': 'test'} - })) + }) self.light_1, self.light_2 = test_light.DEVICES[0:2] @@ -32,8 +32,8 @@ class TestScene(unittest.TestCase): self.hass.block_till_done() - self.assertFalse(self.light_1.is_on) - self.assertFalse(self.light_2.is_on) + assert not self.light_1.is_on + assert not self.light_2.is_on def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" @@ -60,7 +60,7 @@ class TestScene(unittest.TestCase): 'state': 'on', 'brightness': 100, } - self.assertTrue(setup_component(self.hass, scene.DOMAIN, { + assert setup_component(self.hass, scene.DOMAIN, { 'scene': [{ 'name': 'test', 'entities': { @@ -68,17 +68,15 @@ class TestScene(unittest.TestCase): self.light_2.entity_id: entity_state, } }] - })) + }) common.activate(self.hass, 'scene.test') self.hass.block_till_done() - self.assertTrue(self.light_1.is_on) - self.assertTrue(self.light_2.is_on) - self.assertEqual( - 100, self.light_1.last_call('turn_on')[1].get('brightness')) - self.assertEqual( - 100, self.light_2.last_call('turn_on')[1].get('brightness')) + assert self.light_1.is_on + assert self.light_2.is_on + assert 100 == self.light_1.last_call('turn_on')[1].get('brightness') + assert 100 == self.light_2.last_call('turn_on')[1].get('brightness') def test_config_yaml_bool(self): """Test parsing of booleans in yaml config.""" @@ -95,18 +93,17 @@ class TestScene(unittest.TestCase): with io.StringIO(config) as file: doc = yaml.yaml.safe_load(file) - self.assertTrue(setup_component(self.hass, scene.DOMAIN, doc)) + assert setup_component(self.hass, scene.DOMAIN, doc) common.activate(self.hass, 'scene.test') self.hass.block_till_done() - self.assertTrue(self.light_1.is_on) - self.assertTrue(self.light_2.is_on) - self.assertEqual( - 100, self.light_2.last_call('turn_on')[1].get('brightness')) + assert self.light_1.is_on + assert self.light_2.is_on + assert 100 == self.light_2.last_call('turn_on')[1].get('brightness') def test_activate_scene(self): """Test active scene.""" - self.assertTrue(setup_component(self.hass, scene.DOMAIN, { + assert setup_component(self.hass, scene.DOMAIN, { 'scene': [{ 'name': 'test', 'entities': { @@ -117,12 +114,11 @@ class TestScene(unittest.TestCase): } } }] - })) + }) common.activate(self.hass, 'scene.test') self.hass.block_till_done() - self.assertTrue(self.light_1.is_on) - self.assertTrue(self.light_2.is_on) - self.assertEqual( - 100, self.light_2.last_call('turn_on')[1].get('brightness')) + assert self.light_1.is_on + assert self.light_2.is_on + assert 100 == self.light_2.last_call('turn_on')[1].get('brightness') diff --git a/tests/components/sensor/test_bom.py b/tests/components/sensor/test_bom.py index 5e5a82966..50669f5a7 100644 --- a/tests/components/sensor/test_bom.py +++ b/tests/components/sensor/test_bom.py @@ -71,8 +71,8 @@ class TestBOMWeatherSensor(unittest.TestCase): def test_setup(self, mock_get): """Test the setup with custom settings.""" with assert_setup_component(1, sensor.DOMAIN): - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { - 'sensor': VALID_CONFIG})) + assert setup_component(self.hass, sensor.DOMAIN, { + 'sensor': VALID_CONFIG}) fake_entities = [ 'bom_fake_feels_like_c', @@ -81,19 +81,19 @@ class TestBOMWeatherSensor(unittest.TestCase): for entity_id in fake_entities: state = self.hass.states.get('sensor.{}'.format(entity_id)) - self.assertIsNotNone(state) + assert state is not None @patch('requests.get', side_effect=mocked_requests) def test_sensor_values(self, mock_get): """Test retrieval of sensor values.""" - self.assertTrue(setup_component( - self.hass, sensor.DOMAIN, {'sensor': VALID_CONFIG})) + assert setup_component( + self.hass, sensor.DOMAIN, {'sensor': VALID_CONFIG}) weather = self.hass.states.get('sensor.bom_fake_weather').state - self.assertEqual('Fine', weather) + assert 'Fine' == weather pressure = self.hass.states.get('sensor.bom_fake_pressure_mb').state - self.assertEqual('1021.7', pressure) + assert '1021.7' == pressure feels_like = self.hass.states.get('sensor.bom_fake_feels_like_c').state - self.assertEqual('25.0', feels_like) + assert '25.0' == feels_like diff --git a/tests/components/sensor/test_canary.py b/tests/components/sensor/test_canary.py index 47a1f330d..7908e22e5 100644 --- a/tests/components/sensor/test_canary.py +++ b/tests/components/sensor/test_canary.py @@ -53,7 +53,7 @@ class TestCanarySensorSetup(unittest.TestCase): canary.setup_platform(self.hass, self.config, self.add_entities, None) - self.assertEqual(6, len(self.DEVICES)) + assert 6 == len(self.DEVICES) def test_temperature_sensor(self): """Test temperature sensor with fahrenheit.""" @@ -66,10 +66,10 @@ class TestCanarySensorSetup(unittest.TestCase): sensor = CanarySensor(data, SENSOR_TYPES[0], location, device) sensor.update() - self.assertEqual("Home Family Room Temperature", sensor.name) - self.assertEqual("°C", sensor.unit_of_measurement) - self.assertEqual(21.12, sensor.state) - self.assertEqual("mdi:thermometer", sensor.icon) + assert "Home Family Room Temperature" == sensor.name + assert "°C" == sensor.unit_of_measurement + assert 21.12 == sensor.state + assert "mdi:thermometer" == sensor.icon def test_temperature_sensor_with_none_sensor_value(self): """Test temperature sensor with fahrenheit.""" @@ -82,7 +82,7 @@ class TestCanarySensorSetup(unittest.TestCase): sensor = CanarySensor(data, SENSOR_TYPES[0], location, device) sensor.update() - self.assertEqual(None, sensor.state) + assert sensor.state is None def test_humidity_sensor(self): """Test humidity sensor.""" @@ -95,10 +95,10 @@ class TestCanarySensorSetup(unittest.TestCase): sensor = CanarySensor(data, SENSOR_TYPES[1], location, device) sensor.update() - self.assertEqual("Home Family Room Humidity", sensor.name) - self.assertEqual("%", sensor.unit_of_measurement) - self.assertEqual(50.46, sensor.state) - self.assertEqual("mdi:water-percent", sensor.icon) + assert "Home Family Room Humidity" == sensor.name + assert "%" == sensor.unit_of_measurement + assert 50.46 == sensor.state + assert "mdi:water-percent" == sensor.icon def test_air_quality_sensor_with_very_abnormal_reading(self): """Test air quality sensor.""" @@ -111,13 +111,13 @@ class TestCanarySensorSetup(unittest.TestCase): sensor = CanarySensor(data, SENSOR_TYPES[2], location, device) sensor.update() - self.assertEqual("Home Family Room Air Quality", sensor.name) - self.assertEqual(None, sensor.unit_of_measurement) - self.assertEqual(0.4, sensor.state) - self.assertEqual("mdi:weather-windy", sensor.icon) + assert "Home Family Room Air Quality" == sensor.name + assert sensor.unit_of_measurement is None + assert 0.4 == sensor.state + assert "mdi:weather-windy" == sensor.icon air_quality = sensor.device_state_attributes[ATTR_AIR_QUALITY] - self.assertEqual(STATE_AIR_QUALITY_VERY_ABNORMAL, air_quality) + assert STATE_AIR_QUALITY_VERY_ABNORMAL == air_quality def test_air_quality_sensor_with_abnormal_reading(self): """Test air quality sensor.""" @@ -130,13 +130,13 @@ class TestCanarySensorSetup(unittest.TestCase): sensor = CanarySensor(data, SENSOR_TYPES[2], location, device) sensor.update() - self.assertEqual("Home Family Room Air Quality", sensor.name) - self.assertEqual(None, sensor.unit_of_measurement) - self.assertEqual(0.59, sensor.state) - self.assertEqual("mdi:weather-windy", sensor.icon) + assert "Home Family Room Air Quality" == sensor.name + assert sensor.unit_of_measurement is None + assert 0.59 == sensor.state + assert "mdi:weather-windy" == sensor.icon air_quality = sensor.device_state_attributes[ATTR_AIR_QUALITY] - self.assertEqual(STATE_AIR_QUALITY_ABNORMAL, air_quality) + assert STATE_AIR_QUALITY_ABNORMAL == air_quality def test_air_quality_sensor_with_normal_reading(self): """Test air quality sensor.""" @@ -149,13 +149,13 @@ class TestCanarySensorSetup(unittest.TestCase): sensor = CanarySensor(data, SENSOR_TYPES[2], location, device) sensor.update() - self.assertEqual("Home Family Room Air Quality", sensor.name) - self.assertEqual(None, sensor.unit_of_measurement) - self.assertEqual(1.0, sensor.state) - self.assertEqual("mdi:weather-windy", sensor.icon) + assert "Home Family Room Air Quality" == sensor.name + assert sensor.unit_of_measurement is None + assert 1.0 == sensor.state + assert "mdi:weather-windy" == sensor.icon air_quality = sensor.device_state_attributes[ATTR_AIR_QUALITY] - self.assertEqual(STATE_AIR_QUALITY_NORMAL, air_quality) + assert STATE_AIR_QUALITY_NORMAL == air_quality def test_air_quality_sensor_with_none_sensor_value(self): """Test air quality sensor.""" @@ -168,8 +168,8 @@ class TestCanarySensorSetup(unittest.TestCase): sensor = CanarySensor(data, SENSOR_TYPES[2], location, device) sensor.update() - self.assertEqual(None, sensor.state) - self.assertEqual(None, sensor.device_state_attributes) + assert sensor.state is None + assert sensor.device_state_attributes is None def test_battery_sensor(self): """Test battery sensor.""" @@ -182,10 +182,10 @@ class TestCanarySensorSetup(unittest.TestCase): sensor = CanarySensor(data, SENSOR_TYPES[4], location, device) sensor.update() - self.assertEqual("Home Family Room Battery", sensor.name) - self.assertEqual("%", sensor.unit_of_measurement) - self.assertEqual(70.46, sensor.state) - self.assertEqual("mdi:battery-70", sensor.icon) + assert "Home Family Room Battery" == sensor.name + assert "%" == sensor.unit_of_measurement + assert 70.46 == sensor.state + assert "mdi:battery-70" == sensor.icon def test_wifi_sensor(self): """Test battery sensor.""" @@ -198,7 +198,7 @@ class TestCanarySensorSetup(unittest.TestCase): sensor = CanarySensor(data, SENSOR_TYPES[3], location, device) sensor.update() - self.assertEqual("Home Family Room Wifi", sensor.name) - self.assertEqual("dBm", sensor.unit_of_measurement) - self.assertEqual(-57, sensor.state) - self.assertEqual("mdi:wifi", sensor.icon) + assert "Home Family Room Wifi" == sensor.name + assert "dBm" == sensor.unit_of_measurement + assert -57 == sensor.state + assert "mdi:wifi" == sensor.icon diff --git a/tests/components/sensor/test_command_line.py b/tests/components/sensor/test_command_line.py index 82cdef014..cacd7a415 100644 --- a/tests/components/sensor/test_command_line.py +++ b/tests/components/sensor/test_command_line.py @@ -38,12 +38,12 @@ class TestCommandSensorSensor(unittest.TestCase): command_line.setup_platform(self.hass, config, add_dev_callback) - self.assertEqual(1, len(devices)) + assert 1 == len(devices) entity = devices[0] entity.update() - self.assertEqual('Test', entity.name) - self.assertEqual('in', entity.unit_of_measurement) - self.assertEqual('5', entity.state) + assert 'Test' == entity.name + assert 'in' == entity.unit_of_measurement + assert '5' == entity.state def test_template(self): """Test command sensor with template.""" @@ -54,7 +54,7 @@ class TestCommandSensorSensor(unittest.TestCase): Template('{{ value | multiply(0.1) }}', self.hass), []) entity.update() - self.assertEqual(5, float(entity.state)) + assert 5 == float(entity.state) def test_template_render(self): """Ensure command with templates get rendered properly.""" @@ -65,14 +65,14 @@ class TestCommandSensorSensor(unittest.TestCase): ) data.update() - self.assertEqual("Works", data.value) + assert "Works" == data.value def test_bad_command(self): """Test bad command.""" data = command_line.CommandSensorData(self.hass, 'asdfasdf', 15) data.update() - self.assertEqual(None, data.value) + assert data.value is None def test_update_with_json_attrs(self): """Test attributes get extracted from a JSON result.""" @@ -88,12 +88,12 @@ class TestCommandSensorSensor(unittest.TestCase): 'another_key', 'key_three']) self.sensor.update() - self.assertEqual('some_json_value', - self.sensor.device_state_attributes['key']) - self.assertEqual('another_json_value', - self.sensor.device_state_attributes['another_key']) - self.assertEqual('value_three', - self.sensor.device_state_attributes['key_three']) + assert 'some_json_value' == \ + self.sensor.device_state_attributes['key'] + assert 'another_json_value' == \ + self.sensor.device_state_attributes['another_key'] + assert 'value_three' == \ + self.sensor.device_state_attributes['key_three'] @patch('homeassistant.components.sensor.command_line._LOGGER') def test_update_with_json_attrs_no_data(self, mock_logger): @@ -105,8 +105,8 @@ class TestCommandSensorSensor(unittest.TestCase): self.sensor = command_line.CommandSensor(self.hass, data, 'test', None, None, ['key']) self.sensor.update() - self.assertEqual({}, self.sensor.device_state_attributes) - self.assertTrue(mock_logger.warning.called) + assert {} == self.sensor.device_state_attributes + assert mock_logger.warning.called @patch('homeassistant.components.sensor.command_line._LOGGER') def test_update_with_json_attrs_not_dict(self, mock_logger): @@ -118,8 +118,8 @@ class TestCommandSensorSensor(unittest.TestCase): self.sensor = command_line.CommandSensor(self.hass, data, 'test', None, None, ['key']) self.sensor.update() - self.assertEqual({}, self.sensor.device_state_attributes) - self.assertTrue(mock_logger.warning.called) + assert {} == self.sensor.device_state_attributes + assert mock_logger.warning.called @patch('homeassistant.components.sensor.command_line._LOGGER') def test_update_with_json_attrs_bad_JSON(self, mock_logger): @@ -131,8 +131,8 @@ class TestCommandSensorSensor(unittest.TestCase): self.sensor = command_line.CommandSensor(self.hass, data, 'test', None, None, ['key']) self.sensor.update() - self.assertEqual({}, self.sensor.device_state_attributes) - self.assertTrue(mock_logger.warning.called) + assert {} == self.sensor.device_state_attributes + assert mock_logger.warning.called def test_update_with_missing_json_attrs(self): """Test attributes get extracted from a JSON result.""" @@ -149,13 +149,13 @@ class TestCommandSensorSensor(unittest.TestCase): 'key_three', 'special_key']) self.sensor.update() - self.assertEqual('some_json_value', - self.sensor.device_state_attributes['key']) - self.assertEqual('another_json_value', - self.sensor.device_state_attributes['another_key']) - self.assertEqual('value_three', - self.sensor.device_state_attributes['key_three']) - self.assertFalse('special_key' in self.sensor.device_state_attributes) + assert 'some_json_value' == \ + self.sensor.device_state_attributes['key'] + assert 'another_json_value' == \ + self.sensor.device_state_attributes['another_key'] + assert 'value_three' == \ + self.sensor.device_state_attributes['key_three'] + assert not ('special_key' in self.sensor.device_state_attributes) def test_update_with_unnecessary_json_attrs(self): """Test attributes get extracted from a JSON result.""" @@ -170,8 +170,8 @@ class TestCommandSensorSensor(unittest.TestCase): None, None, ['key', 'another_key']) self.sensor.update() - self.assertEqual('some_json_value', - self.sensor.device_state_attributes['key']) - self.assertEqual('another_json_value', - self.sensor.device_state_attributes['another_key']) - self.assertFalse('key_three' in self.sensor.device_state_attributes) + assert 'some_json_value' == \ + self.sensor.device_state_attributes['key'] + assert 'another_json_value' == \ + self.sensor.device_state_attributes['another_key'] + assert not ('key_three' in self.sensor.device_state_attributes) diff --git a/tests/components/sensor/test_darksky.py b/tests/components/sensor/test_darksky.py index 9300ecef4..fb3c89db0 100644 --- a/tests/components/sensor/test_darksky.py +++ b/tests/components/sensor/test_darksky.py @@ -140,7 +140,7 @@ class TestDarkSkySetup(unittest.TestCase): response = darksky.setup_platform(self.hass, VALID_CONFIG_MINIMAL, MagicMock()) - self.assertFalse(response) + assert not response @requests_mock.Mocker() @patch('forecastio.api.get_forecast', wraps=forecastio.api.get_forecast) @@ -152,12 +152,12 @@ class TestDarkSkySetup(unittest.TestCase): assert setup_component(self.hass, 'sensor', VALID_CONFIG_MINIMAL) - self.assertTrue(mock_get_forecast.called) - self.assertEqual(mock_get_forecast.call_count, 1) - self.assertEqual(len(self.hass.states.entity_ids()), 7) + assert mock_get_forecast.called + assert mock_get_forecast.call_count == 1 + assert len(self.hass.states.entity_ids()) == 7 state = self.hass.states.get('sensor.dark_sky_summary') assert state is not None - self.assertEqual(state.state, 'Clear') - self.assertEqual(state.attributes.get('friendly_name'), - 'Dark Sky Summary') + assert state.state == 'Clear' + assert state.attributes.get('friendly_name') == \ + 'Dark Sky Summary' diff --git a/tests/components/sensor/test_dte_energy_bridge.py b/tests/components/sensor/test_dte_energy_bridge.py index 2341c3f83..335f5d67a 100644 --- a/tests/components/sensor/test_dte_energy_bridge.py +++ b/tests/components/sensor/test_dte_energy_bridge.py @@ -27,9 +27,8 @@ class TestDteEnergyBridgeSetup(unittest.TestCase): def test_setup_with_config(self): """Test the platform setup with configuration.""" - self.assertTrue( - setup_component(self.hass, 'sensor', - {'dte_energy_bridge': DTE_ENERGY_BRIDGE_CONFIG})) + assert setup_component(self.hass, 'sensor', + {'dte_energy_bridge': DTE_ENERGY_BRIDGE_CONFIG}) @requests_mock.Mocker() def test_setup_correct_reading(self, mock_req): @@ -39,9 +38,9 @@ class TestDteEnergyBridgeSetup(unittest.TestCase): text='.411 kW') assert setup_component(self.hass, 'sensor', { 'sensor': DTE_ENERGY_BRIDGE_CONFIG}) - self.assertEqual('0.411', - self.hass.states - .get('sensor.current_energy_usage').state) + assert '0.411' == \ + self.hass.states \ + .get('sensor.current_energy_usage').state @requests_mock.Mocker() def test_setup_incorrect_units_reading(self, mock_req): @@ -51,9 +50,9 @@ class TestDteEnergyBridgeSetup(unittest.TestCase): text='411 kW') assert setup_component(self.hass, 'sensor', { 'sensor': DTE_ENERGY_BRIDGE_CONFIG}) - self.assertEqual('0.411', - self.hass.states - .get('sensor.current_energy_usage').state) + assert '0.411' == \ + self.hass.states \ + .get('sensor.current_energy_usage').state @requests_mock.Mocker() def test_setup_bad_format_reading(self, mock_req): @@ -63,6 +62,6 @@ class TestDteEnergyBridgeSetup(unittest.TestCase): text='411') assert setup_component(self.hass, 'sensor', { 'sensor': DTE_ENERGY_BRIDGE_CONFIG}) - self.assertEqual('unknown', - self.hass.states - .get('sensor.current_energy_usage').state) + assert 'unknown' == \ + self.hass.states \ + .get('sensor.current_energy_usage').state diff --git a/tests/components/sensor/test_dyson.py b/tests/components/sensor/test_dyson.py index baab96a61..d4609c2b2 100644 --- a/tests/components/sensor/test_dyson.py +++ b/tests/components/sensor/test_dyson.py @@ -86,11 +86,11 @@ class DysonTest(unittest.TestCase): sensor = dyson.DysonFilterLifeSensor(_get_device_without_state()) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertIsNone(sensor.state) - self.assertEqual(sensor.unit_of_measurement, "hours") - self.assertEqual(sensor.name, "Device_name Filter Life") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state is None + assert sensor.unit_of_measurement == "hours" + assert sensor.name == "Device_name Filter Life" + assert sensor.entity_id == "sensor.dyson_1" sensor.on_message('message') def test_dyson_filter_life_sensor_with_values(self): @@ -98,11 +98,11 @@ class DysonTest(unittest.TestCase): sensor = dyson.DysonFilterLifeSensor(_get_with_state()) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertEqual(sensor.state, 100) - self.assertEqual(sensor.unit_of_measurement, "hours") - self.assertEqual(sensor.name, "Device_name Filter Life") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state == 100 + assert sensor.unit_of_measurement == "hours" + assert sensor.name == "Device_name Filter Life" + assert sensor.entity_id == "sensor.dyson_1" sensor.on_message('message') def test_dyson_dust_sensor(self): @@ -110,55 +110,55 @@ class DysonTest(unittest.TestCase): sensor = dyson.DysonDustSensor(_get_device_without_state()) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertIsNone(sensor.state) - self.assertEqual(sensor.unit_of_measurement, None) - self.assertEqual(sensor.name, "Device_name Dust") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state is None + assert sensor.unit_of_measurement is None + assert sensor.name == "Device_name Dust" + assert sensor.entity_id == "sensor.dyson_1" def test_dyson_dust_sensor_with_values(self): """Test dust sensor with values.""" sensor = dyson.DysonDustSensor(_get_with_state()) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertEqual(sensor.state, 5) - self.assertEqual(sensor.unit_of_measurement, None) - self.assertEqual(sensor.name, "Device_name Dust") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state == 5 + assert sensor.unit_of_measurement is None + assert sensor.name == "Device_name Dust" + assert sensor.entity_id == "sensor.dyson_1" def test_dyson_humidity_sensor(self): """Test humidity sensor with no value.""" sensor = dyson.DysonHumiditySensor(_get_device_without_state()) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertIsNone(sensor.state) - self.assertEqual(sensor.unit_of_measurement, '%') - self.assertEqual(sensor.name, "Device_name Humidity") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state is None + assert sensor.unit_of_measurement == '%' + assert sensor.name == "Device_name Humidity" + assert sensor.entity_id == "sensor.dyson_1" def test_dyson_humidity_sensor_with_values(self): """Test humidity sensor with values.""" sensor = dyson.DysonHumiditySensor(_get_with_state()) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertEqual(sensor.state, 45) - self.assertEqual(sensor.unit_of_measurement, '%') - self.assertEqual(sensor.name, "Device_name Humidity") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state == 45 + assert sensor.unit_of_measurement == '%' + assert sensor.name == "Device_name Humidity" + assert sensor.entity_id == "sensor.dyson_1" def test_dyson_humidity_standby_monitoring(self): """Test humidity sensor while device is in standby monitoring.""" sensor = dyson.DysonHumiditySensor(_get_with_standby_monitoring()) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertEqual(sensor.state, STATE_OFF) - self.assertEqual(sensor.unit_of_measurement, '%') - self.assertEqual(sensor.name, "Device_name Humidity") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state == STATE_OFF + assert sensor.unit_of_measurement == '%' + assert sensor.name == "Device_name Humidity" + assert sensor.entity_id == "sensor.dyson_1" def test_dyson_temperature_sensor(self): """Test temperature sensor with no value.""" @@ -166,11 +166,11 @@ class DysonTest(unittest.TestCase): TEMP_CELSIUS) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertIsNone(sensor.state) - self.assertEqual(sensor.unit_of_measurement, '°C') - self.assertEqual(sensor.name, "Device_name Temperature") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state is None + assert sensor.unit_of_measurement == '°C' + assert sensor.name == "Device_name Temperature" + assert sensor.entity_id == "sensor.dyson_1" def test_dyson_temperature_sensor_with_values(self): """Test temperature sensor with values.""" @@ -178,21 +178,21 @@ class DysonTest(unittest.TestCase): TEMP_CELSIUS) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertEqual(sensor.state, 21.9) - self.assertEqual(sensor.unit_of_measurement, '°C') - self.assertEqual(sensor.name, "Device_name Temperature") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state == 21.9 + assert sensor.unit_of_measurement == '°C' + assert sensor.name == "Device_name Temperature" + assert sensor.entity_id == "sensor.dyson_1" sensor = dyson.DysonTemperatureSensor(_get_with_state(), TEMP_FAHRENHEIT) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertEqual(sensor.state, 71.3) - self.assertEqual(sensor.unit_of_measurement, '°F') - self.assertEqual(sensor.name, "Device_name Temperature") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state == 71.3 + assert sensor.unit_of_measurement == '°F' + assert sensor.name == "Device_name Temperature" + assert sensor.entity_id == "sensor.dyson_1" def test_dyson_temperature_standby_monitoring(self): """Test temperature sensor while device is in standby monitoring.""" @@ -200,30 +200,30 @@ class DysonTest(unittest.TestCase): TEMP_CELSIUS) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertEqual(sensor.state, STATE_OFF) - self.assertEqual(sensor.unit_of_measurement, '°C') - self.assertEqual(sensor.name, "Device_name Temperature") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state == STATE_OFF + assert sensor.unit_of_measurement == '°C' + assert sensor.name == "Device_name Temperature" + assert sensor.entity_id == "sensor.dyson_1" def test_dyson_air_quality_sensor(self): """Test air quality sensor with no value.""" sensor = dyson.DysonAirQualitySensor(_get_device_without_state()) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertIsNone(sensor.state) - self.assertEqual(sensor.unit_of_measurement, None) - self.assertEqual(sensor.name, "Device_name AQI") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state is None + assert sensor.unit_of_measurement is None + assert sensor.name == "Device_name AQI" + assert sensor.entity_id == "sensor.dyson_1" def test_dyson_air_quality_sensor_with_values(self): """Test air quality sensor with values.""" sensor = dyson.DysonAirQualitySensor(_get_with_state()) sensor.hass = self.hass sensor.entity_id = "sensor.dyson_1" - self.assertFalse(sensor.should_poll) - self.assertEqual(sensor.state, 2) - self.assertEqual(sensor.unit_of_measurement, None) - self.assertEqual(sensor.name, "Device_name AQI") - self.assertEqual(sensor.entity_id, "sensor.dyson_1") + assert not sensor.should_poll + assert sensor.state == 2 + assert sensor.unit_of_measurement is None + assert sensor.name == "Device_name AQI" + assert sensor.entity_id == "sensor.dyson_1" diff --git a/tests/components/sensor/test_efergy.py b/tests/components/sensor/test_efergy.py index fdcaa4154..f35c7b143 100644 --- a/tests/components/sensor/test_efergy.py +++ b/tests/components/sensor/test_efergy.py @@ -85,16 +85,11 @@ class TestEfergySensor(unittest.TestCase): 'sensor': ONE_SENSOR_CONFIG, }) - self.assertEqual( - '38.21', self.hass.states.get('sensor.energy_consumed').state) - self.assertEqual( - '1580', self.hass.states.get('sensor.energy_usage').state) - self.assertEqual( - 'ok', self.hass.states.get('sensor.energy_budget').state) - self.assertEqual( - '5.27', self.hass.states.get('sensor.energy_cost').state) - self.assertEqual( - '1628', self.hass.states.get('sensor.efergy_728386').state) + assert '38.21' == self.hass.states.get('sensor.energy_consumed').state + assert '1580' == self.hass.states.get('sensor.energy_usage').state + assert 'ok' == self.hass.states.get('sensor.energy_budget').state + assert '5.27' == self.hass.states.get('sensor.energy_cost').state + assert '1628' == self.hass.states.get('sensor.efergy_728386').state @requests_mock.Mocker() def test_multi_sensor_readings(self, mock): @@ -104,9 +99,6 @@ class TestEfergySensor(unittest.TestCase): 'sensor': MULTI_SENSOR_CONFIG, }) - self.assertEqual( - '218', self.hass.states.get('sensor.efergy_728386').state) - self.assertEqual( - '1808', self.hass.states.get('sensor.efergy_0').state) - self.assertEqual( - '312', self.hass.states.get('sensor.efergy_728387').state) + assert '218' == self.hass.states.get('sensor.efergy_728386').state + assert '1808' == self.hass.states.get('sensor.efergy_0').state + assert '312' == self.hass.states.get('sensor.efergy_728387').state diff --git a/tests/components/sensor/test_fail2ban.py b/tests/components/sensor/test_fail2ban.py index a6131e5db..6ba959f80 100644 --- a/tests/components/sensor/test_fail2ban.py +++ b/tests/components/sensor/test_fail2ban.py @@ -101,120 +101,99 @@ class TestBanSensor(unittest.TestCase): """Test that log is parsed correctly for single ban.""" log_parser = BanLogParser(timedelta(seconds=-1), '/tmp') sensor = BanSensor('fail2ban', 'jail_one', log_parser) - self.assertEqual(sensor.name, 'fail2ban jail_one') + assert sensor.name == 'fail2ban jail_one' mock_fh = MockOpen(read_data=fake_log('single_ban')) with patch('homeassistant.components.sensor.fail2ban.open', mock_fh, create=True): sensor.update() - self.assertEqual(sensor.state, '111.111.111.111') - self.assertEqual( - sensor.state_attributes[STATE_CURRENT_BANS], ['111.111.111.111'] - ) - self.assertEqual( - sensor.state_attributes[STATE_ALL_BANS], ['111.111.111.111'] - ) + assert sensor.state == '111.111.111.111' + assert \ + sensor.state_attributes[STATE_CURRENT_BANS] == ['111.111.111.111'] + assert \ + sensor.state_attributes[STATE_ALL_BANS] == ['111.111.111.111'] def test_multiple_ban(self): """Test that log is parsed correctly for multiple ban.""" log_parser = BanLogParser(timedelta(seconds=-1), '/tmp') sensor = BanSensor('fail2ban', 'jail_one', log_parser) - self.assertEqual(sensor.name, 'fail2ban jail_one') + assert sensor.name == 'fail2ban jail_one' mock_fh = MockOpen(read_data=fake_log('multi_ban')) with patch('homeassistant.components.sensor.fail2ban.open', mock_fh, create=True): sensor.update() - self.assertEqual(sensor.state, '222.222.222.222') - self.assertEqual( - sensor.state_attributes[STATE_CURRENT_BANS], + assert sensor.state == '222.222.222.222' + assert sensor.state_attributes[STATE_CURRENT_BANS] == \ ['111.111.111.111', '222.222.222.222'] - ) - self.assertEqual( - sensor.state_attributes[STATE_ALL_BANS], + assert sensor.state_attributes[STATE_ALL_BANS] == \ ['111.111.111.111', '222.222.222.222'] - ) def test_unban_all(self): """Test that log is parsed correctly when unbanning.""" log_parser = BanLogParser(timedelta(seconds=-1), '/tmp') sensor = BanSensor('fail2ban', 'jail_one', log_parser) - self.assertEqual(sensor.name, 'fail2ban jail_one') + assert sensor.name == 'fail2ban jail_one' mock_fh = MockOpen(read_data=fake_log('unban_all')) with patch('homeassistant.components.sensor.fail2ban.open', mock_fh, create=True): sensor.update() - self.assertEqual(sensor.state, 'None') - self.assertEqual(sensor.state_attributes[STATE_CURRENT_BANS], []) - self.assertEqual( - sensor.state_attributes[STATE_ALL_BANS], + assert sensor.state == 'None' + assert sensor.state_attributes[STATE_CURRENT_BANS] == [] + assert sensor.state_attributes[STATE_ALL_BANS] == \ ['111.111.111.111', '222.222.222.222'] - ) def test_unban_one(self): """Test that log is parsed correctly when unbanning one ip.""" log_parser = BanLogParser(timedelta(seconds=-1), '/tmp') sensor = BanSensor('fail2ban', 'jail_one', log_parser) - self.assertEqual(sensor.name, 'fail2ban jail_one') + assert sensor.name == 'fail2ban jail_one' mock_fh = MockOpen(read_data=fake_log('unban_one')) with patch('homeassistant.components.sensor.fail2ban.open', mock_fh, create=True): sensor.update() - self.assertEqual(sensor.state, '222.222.222.222') - self.assertEqual( - sensor.state_attributes[STATE_CURRENT_BANS], + assert sensor.state == '222.222.222.222' + assert sensor.state_attributes[STATE_CURRENT_BANS] == \ ['222.222.222.222'] - ) - self.assertEqual( - sensor.state_attributes[STATE_ALL_BANS], + assert sensor.state_attributes[STATE_ALL_BANS] == \ ['111.111.111.111', '222.222.222.222'] - ) def test_multi_jail(self): """Test that log is parsed correctly when using multiple jails.""" log_parser = BanLogParser(timedelta(seconds=-1), '/tmp') sensor1 = BanSensor('fail2ban', 'jail_one', log_parser) sensor2 = BanSensor('fail2ban', 'jail_two', log_parser) - self.assertEqual(sensor1.name, 'fail2ban jail_one') - self.assertEqual(sensor2.name, 'fail2ban jail_two') + assert sensor1.name == 'fail2ban jail_one' + assert sensor2.name == 'fail2ban jail_two' mock_fh = MockOpen(read_data=fake_log('multi_jail')) with patch('homeassistant.components.sensor.fail2ban.open', mock_fh, create=True): sensor1.update() sensor2.update() - self.assertEqual(sensor1.state, '111.111.111.111') - self.assertEqual( - sensor1.state_attributes[STATE_CURRENT_BANS], ['111.111.111.111'] - ) - self.assertEqual( - sensor1.state_attributes[STATE_ALL_BANS], ['111.111.111.111'] - ) - self.assertEqual(sensor2.state, '222.222.222.222') - self.assertEqual( - sensor2.state_attributes[STATE_CURRENT_BANS], ['222.222.222.222'] - ) - self.assertEqual( - sensor2.state_attributes[STATE_ALL_BANS], ['222.222.222.222'] - ) + assert sensor1.state == '111.111.111.111' + assert \ + sensor1.state_attributes[STATE_CURRENT_BANS] == ['111.111.111.111'] + assert sensor1.state_attributes[STATE_ALL_BANS] == ['111.111.111.111'] + assert sensor2.state == '222.222.222.222' + assert \ + sensor2.state_attributes[STATE_CURRENT_BANS] == ['222.222.222.222'] + assert sensor2.state_attributes[STATE_ALL_BANS] == ['222.222.222.222'] def test_ban_active_after_update(self): """Test that ban persists after subsequent update.""" log_parser = BanLogParser(timedelta(seconds=-1), '/tmp') sensor = BanSensor('fail2ban', 'jail_one', log_parser) - self.assertEqual(sensor.name, 'fail2ban jail_one') + assert sensor.name == 'fail2ban jail_one' mock_fh = MockOpen(read_data=fake_log('single_ban')) with patch('homeassistant.components.sensor.fail2ban.open', mock_fh, create=True): sensor.update() - self.assertEqual(sensor.state, '111.111.111.111') + assert sensor.state == '111.111.111.111' sensor.update() - self.assertEqual(sensor.state, '111.111.111.111') - self.assertEqual( - sensor.state_attributes[STATE_CURRENT_BANS], ['111.111.111.111'] - ) - self.assertEqual( - sensor.state_attributes[STATE_ALL_BANS], ['111.111.111.111'] - ) + assert sensor.state == '111.111.111.111' + assert \ + sensor.state_attributes[STATE_CURRENT_BANS] == ['111.111.111.111'] + assert sensor.state_attributes[STATE_ALL_BANS] == ['111.111.111.111'] diff --git a/tests/components/sensor/test_file.py b/tests/components/sensor/test_file.py index 7171289de..3ac37b989 100644 --- a/tests/components/sensor/test_file.py +++ b/tests/components/sensor/test_file.py @@ -45,7 +45,7 @@ class TestFileSensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('sensor.file1') - self.assertEqual(state.state, '21') + assert state.state == '21' @patch('os.path.isfile', Mock(return_value=True)) @patch('os.access', Mock(return_value=True)) @@ -70,7 +70,7 @@ class TestFileSensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('sensor.file2') - self.assertEqual(state.state, '26') + assert state.state == '26' @patch('os.path.isfile', Mock(return_value=True)) @patch('os.access', Mock(return_value=True)) @@ -91,4 +91,4 @@ class TestFileSensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('sensor.file3') - self.assertEqual(state.state, STATE_UNKNOWN) + assert state.state == STATE_UNKNOWN diff --git a/tests/components/sensor/test_filesize.py b/tests/components/sensor/test_filesize.py index 23ef1c608..f0ea5c95d 100644 --- a/tests/components/sensor/test_filesize.py +++ b/tests/components/sensor/test_filesize.py @@ -38,8 +38,7 @@ class TestFileSensor(unittest.TestCase): 'platform': 'filesize', CONF_FILE_PATHS: ['invalid_path']} } - self.assertTrue( - setup_component(self.hass, 'sensor', config)) + assert setup_component(self.hass, 'sensor', config) assert len(self.hass.states.entity_ids()) == 0 def test_valid_path(self): @@ -50,8 +49,7 @@ class TestFileSensor(unittest.TestCase): 'platform': 'filesize', CONF_FILE_PATHS: [TEST_FILE]} } - self.assertTrue( - setup_component(self.hass, 'sensor', config)) + assert setup_component(self.hass, 'sensor', config) assert len(self.hass.states.entity_ids()) == 1 state = self.hass.states.get('sensor.mock_file_test_filesizetxt') assert state.state == '0.0' diff --git a/tests/components/sensor/test_filter.py b/tests/components/sensor/test_filter.py index 433d1aa25..3d44b7d13 100644 --- a/tests/components/sensor/test_filter.py +++ b/tests/components/sensor/test_filter.py @@ -99,7 +99,7 @@ class TestFilterSensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('sensor.test') - self.assertEqual('17.05', state.state) + assert '17.05' == state.state def test_outlier(self): """Test if outlier filter works.""" @@ -109,7 +109,7 @@ class TestFilterSensor(unittest.TestCase): radius=4.0) for state in self.values: filtered = filt.filter_state(state) - self.assertEqual(22, filtered.state) + assert 22 == filtered.state def test_initial_outlier(self): """Test issue #13363.""" @@ -120,7 +120,7 @@ class TestFilterSensor(unittest.TestCase): out = ha.State('sensor.test_monitored', 4000) for state in [out]+self.values: filtered = filt.filter_state(state) - self.assertEqual(22, filtered.state) + assert 22 == filtered.state def test_lowpass(self): """Test if lowpass filter works.""" @@ -130,7 +130,7 @@ class TestFilterSensor(unittest.TestCase): time_constant=10) for state in self.values: filtered = filt.filter_state(state) - self.assertEqual(18.05, filtered.state) + assert 18.05 == filtered.state def test_range(self): """Test if range filter works.""" @@ -143,11 +143,11 @@ class TestFilterSensor(unittest.TestCase): unf = float(unf_state.state) filtered = filt.filter_state(unf_state) if unf < lower: - self.assertEqual(lower, filtered.state) + assert lower == filtered.state elif unf > upper: - self.assertEqual(upper, filtered.state) + assert upper == filtered.state else: - self.assertEqual(unf, filtered.state) + assert unf == filtered.state def test_range_zero(self): """Test if range filter works with zeroes as bounds.""" @@ -160,11 +160,11 @@ class TestFilterSensor(unittest.TestCase): unf = float(unf_state.state) filtered = filt.filter_state(unf_state) if unf < lower: - self.assertEqual(lower, filtered.state) + assert lower == filtered.state elif unf > upper: - self.assertEqual(upper, filtered.state) + assert upper == filtered.state else: - self.assertEqual(unf, filtered.state) + assert unf == filtered.state def test_throttle(self): """Test if lowpass filter works.""" @@ -176,7 +176,7 @@ class TestFilterSensor(unittest.TestCase): new_state = filt.filter_state(state) if not filt.skip_processing: filtered.append(new_state) - self.assertEqual([20, 21], [f.state for f in filtered]) + assert [20, 21] == [f.state for f in filtered] def test_time_sma(self): """Test if time_sma filter works.""" @@ -186,4 +186,4 @@ class TestFilterSensor(unittest.TestCase): type='last') for state in self.values: filtered = filt.filter_state(state) - self.assertEqual(21.5, filtered.state) + assert 21.5 == filtered.state diff --git a/tests/components/sensor/test_folder.py b/tests/components/sensor/test_folder.py index 85ae8a688..e4f97fbaa 100644 --- a/tests/components/sensor/test_folder.py +++ b/tests/components/sensor/test_folder.py @@ -44,8 +44,7 @@ class TestFolderSensor(unittest.TestCase): 'platform': 'folder', CONF_FOLDER_PATHS: 'invalid_path'} } - self.assertTrue( - setup_component(self.hass, 'sensor', config)) + assert setup_component(self.hass, 'sensor', config) assert len(self.hass.states.entity_ids()) == 0 def test_valid_path(self): @@ -56,8 +55,7 @@ class TestFolderSensor(unittest.TestCase): 'platform': 'folder', CONF_FOLDER_PATHS: TEST_DIR} } - self.assertTrue( - setup_component(self.hass, 'sensor', config)) + assert setup_component(self.hass, 'sensor', config) assert len(self.hass.states.entity_ids()) == 1 state = self.hass.states.get('sensor.test_folder') assert state.state == '0.0' diff --git a/tests/components/sensor/test_geo_rss_events.py b/tests/components/sensor/test_geo_rss_events.py index 3362f7993..988b7b686 100644 --- a/tests/components/sensor/test_geo_rss_events.py +++ b/tests/components/sensor/test_geo_rss_events.py @@ -81,8 +81,7 @@ class TestGeoRssServiceUpdater(unittest.TestCase): # Patching 'utcnow' to gain more control over the timed update. with patch('homeassistant.util.dt.utcnow', return_value=utcnow): with assert_setup_component(1, sensor.DOMAIN): - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, - VALID_CONFIG)) + assert setup_component(self.hass, sensor.DOMAIN, VALID_CONFIG) # Artificially trigger update. self.hass.bus.fire(EVENT_HOMEASSISTANT_START) # Collect events. @@ -92,7 +91,7 @@ class TestGeoRssServiceUpdater(unittest.TestCase): assert len(all_states) == 1 state = self.hass.states.get("sensor.event_service_any") - self.assertIsNotNone(state) + assert state is not None assert state.name == "Event Service Any" assert int(state.state) == 2 assert state.attributes == { @@ -142,8 +141,8 @@ class TestGeoRssServiceUpdater(unittest.TestCase): mock_entry_2] with assert_setup_component(1, sensor.DOMAIN): - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, - VALID_CONFIG_WITH_CATEGORIES)) + assert setup_component(self.hass, sensor.DOMAIN, + VALID_CONFIG_WITH_CATEGORIES) # Artificially trigger update. self.hass.bus.fire(EVENT_HOMEASSISTANT_START) # Collect events. @@ -153,7 +152,7 @@ class TestGeoRssServiceUpdater(unittest.TestCase): assert len(all_states) == 1 state = self.hass.states.get("sensor.event_service_category_1") - self.assertIsNotNone(state) + assert state is not None assert state.name == "Event Service Category 1" assert int(state.state) == 2 assert state.attributes == { diff --git a/tests/components/sensor/test_google_wifi.py b/tests/components/sensor/test_google_wifi.py index 55afedab5..a4b18d0ed 100644 --- a/tests/components/sensor/test_google_wifi.py +++ b/tests/components/sensor/test_google_wifi.py @@ -49,12 +49,12 @@ class TestGoogleWifiSetup(unittest.TestCase): resource = '{}{}{}'.format( 'http://', google_wifi.DEFAULT_HOST, google_wifi.ENDPOINT) mock_req.get(resource, status_code=200) - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': { 'platform': 'google_wifi', 'monitored_conditions': ['uptime'] } - })) + }) assert_setup_component(1, 'sensor') @requests_mock.Mocker() @@ -63,7 +63,7 @@ class TestGoogleWifiSetup(unittest.TestCase): resource = '{}{}{}'.format( 'http://', 'localhost', google_wifi.ENDPOINT) mock_req.get(resource, status_code=200) - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': { 'platform': 'google_wifi', 'host': 'localhost', @@ -75,7 +75,7 @@ class TestGoogleWifiSetup(unittest.TestCase): 'local_ip', 'status'] } - })) + }) assert_setup_component(6, 'sensor') @@ -127,20 +127,20 @@ class TestGoogleWifiSensor(unittest.TestCase): for name in self.sensor_dict: sensor = self.sensor_dict[name]['sensor'] test_name = self.sensor_dict[name]['name'] - self.assertEqual(test_name, sensor.name) + assert test_name == sensor.name def test_unit_of_measurement(self): """Test the unit of measurement.""" for name in self.sensor_dict: sensor = self.sensor_dict[name]['sensor'] - self.assertEqual( - self.sensor_dict[name]['units'], sensor.unit_of_measurement) + assert \ + self.sensor_dict[name]['units'] == sensor.unit_of_measurement def test_icon(self): """Test the icon.""" for name in self.sensor_dict: sensor = self.sensor_dict[name]['sensor'] - self.assertEqual(self.sensor_dict[name]['icon'], sensor.icon) + assert self.sensor_dict[name]['icon'] == sensor.icon @requests_mock.Mocker() def test_state(self, mock_req): @@ -153,13 +153,13 @@ class TestGoogleWifiSensor(unittest.TestCase): self.fake_delay(2) sensor.update() if name == google_wifi.ATTR_LAST_RESTART: - self.assertEqual('1969-12-31 00:00:00', sensor.state) + assert '1969-12-31 00:00:00' == sensor.state elif name == google_wifi.ATTR_UPTIME: - self.assertEqual(1, sensor.state) + assert 1 == sensor.state elif name == google_wifi.ATTR_STATUS: - self.assertEqual('Online', sensor.state) + assert 'Online' == sensor.state else: - self.assertEqual('initial', sensor.state) + assert 'initial' == sensor.state @requests_mock.Mocker() def test_update_when_value_is_none(self, mock_req): @@ -169,7 +169,7 @@ class TestGoogleWifiSensor(unittest.TestCase): sensor = self.sensor_dict[name]['sensor'] self.fake_delay(2) sensor.update() - self.assertEqual(STATE_UNKNOWN, sensor.state) + assert STATE_UNKNOWN == sensor.state @requests_mock.Mocker() def test_update_when_value_changed(self, mock_req): @@ -182,17 +182,17 @@ class TestGoogleWifiSensor(unittest.TestCase): self.fake_delay(2) sensor.update() if name == google_wifi.ATTR_LAST_RESTART: - self.assertEqual('1969-12-30 00:00:00', sensor.state) + assert '1969-12-30 00:00:00' == sensor.state elif name == google_wifi.ATTR_UPTIME: - self.assertEqual(2, sensor.state) + assert 2 == sensor.state elif name == google_wifi.ATTR_STATUS: - self.assertEqual('Offline', sensor.state) + assert 'Offline' == sensor.state elif name == google_wifi.ATTR_NEW_VERSION: - self.assertEqual('Latest', sensor.state) + assert 'Latest' == sensor.state elif name == google_wifi.ATTR_LOCAL_IP: - self.assertEqual(STATE_UNKNOWN, sensor.state) + assert STATE_UNKNOWN == sensor.state else: - self.assertEqual('next', sensor.state) + assert 'next' == sensor.state @requests_mock.Mocker() def test_when_api_data_missing(self, mock_req): @@ -204,7 +204,7 @@ class TestGoogleWifiSensor(unittest.TestCase): sensor = self.sensor_dict[name]['sensor'] self.fake_delay(2) sensor.update() - self.assertEqual(STATE_UNKNOWN, sensor.state) + assert STATE_UNKNOWN == sensor.state def test_update_when_unavailable(self): """Test state updates when Google Wifi unavailable.""" @@ -213,7 +213,7 @@ class TestGoogleWifiSensor(unittest.TestCase): for name in self.sensor_dict: sensor = self.sensor_dict[name]['sensor'] sensor.update() - self.assertEqual(STATE_UNKNOWN, sensor.state) + assert STATE_UNKNOWN == sensor.state def update_side_effect(self): """Mock representation of update function.""" diff --git a/tests/components/sensor/test_hddtemp.py b/tests/components/sensor/test_hddtemp.py index 1b65af7fd..eeca7fcf5 100644 --- a/tests/components/sensor/test_hddtemp.py +++ b/tests/components/sensor/test_hddtemp.py @@ -129,13 +129,13 @@ class TestHDDTempSensor(unittest.TestCase): reference = self.reference[state.attributes.get('device')] - self.assertEqual(state.state, reference['temperature']) - self.assertEqual(state.attributes.get('device'), reference['device']) - self.assertEqual(state.attributes.get('model'), reference['model']) - self.assertEqual(state.attributes.get('unit_of_measurement'), - reference['unit_of_measurement']) - self.assertEqual(state.attributes.get('friendly_name'), - 'HD Temperature ' + reference['device']) + assert state.state == reference['temperature'] + assert state.attributes.get('device') == reference['device'] + assert state.attributes.get('model') == reference['model'] + assert state.attributes.get('unit_of_measurement') == \ + reference['unit_of_measurement'] + assert state.attributes.get('friendly_name') == \ + 'HD Temperature ' + reference['device'] @patch('telnetlib.Telnet', new=TelnetMock) def test_hddtemp_rename_config(self): @@ -147,8 +147,8 @@ class TestHDDTempSensor(unittest.TestCase): reference = self.reference[state.attributes.get('device')] - self.assertEqual(state.attributes.get('friendly_name'), - 'FooBar ' + reference['device']) + assert state.attributes.get('friendly_name') == \ + 'FooBar ' + reference['device'] @patch('telnetlib.Telnet', new=TelnetMock) def test_hddtemp_one_disk(self): @@ -159,23 +159,23 @@ class TestHDDTempSensor(unittest.TestCase): reference = self.reference[state.attributes.get('device')] - self.assertEqual(state.state, reference['temperature']) - self.assertEqual(state.attributes.get('device'), reference['device']) - self.assertEqual(state.attributes.get('model'), reference['model']) - self.assertEqual(state.attributes.get('unit_of_measurement'), - reference['unit_of_measurement']) - self.assertEqual(state.attributes.get('friendly_name'), - 'HD Temperature ' + reference['device']) + assert state.state == reference['temperature'] + assert state.attributes.get('device') == reference['device'] + assert state.attributes.get('model') == reference['model'] + assert state.attributes.get('unit_of_measurement') == \ + reference['unit_of_measurement'] + assert state.attributes.get('friendly_name') == \ + 'HD Temperature ' + reference['device'] @patch('telnetlib.Telnet', new=TelnetMock) def test_hddtemp_wrong_disk(self): """Test hddtemp wrong disk configuration.""" assert setup_component(self.hass, 'sensor', VALID_CONFIG_WRONG_DISK) - self.assertEqual(len(self.hass.states.all()), 1) + assert len(self.hass.states.all()) == 1 state = self.hass.states.get('sensor.hd_temperature_devsdx1') - self.assertEqual(state.attributes.get('friendly_name'), - 'HD Temperature ' + '/dev/sdx1') + assert state.attributes.get('friendly_name') == \ + 'HD Temperature ' + '/dev/sdx1' @patch('telnetlib.Telnet', new=TelnetMock) def test_hddtemp_multiple_disks(self): @@ -191,26 +191,26 @@ class TestHDDTempSensor(unittest.TestCase): reference = self.reference[state.attributes.get('device')] - self.assertEqual(state.state, - reference['temperature']) - self.assertEqual(state.attributes.get('device'), - reference['device']) - self.assertEqual(state.attributes.get('model'), - reference['model']) - self.assertEqual(state.attributes.get('unit_of_measurement'), - reference['unit_of_measurement']) - self.assertEqual(state.attributes.get('friendly_name'), - 'HD Temperature ' + reference['device']) + assert state.state == \ + reference['temperature'] + assert state.attributes.get('device') == \ + reference['device'] + assert state.attributes.get('model') == \ + reference['model'] + assert state.attributes.get('unit_of_measurement') == \ + reference['unit_of_measurement'] + assert state.attributes.get('friendly_name') == \ + 'HD Temperature ' + reference['device'] @patch('telnetlib.Telnet', new=TelnetMock) def test_hddtemp_host_refused(self): """Test hddtemp if host unreachable.""" assert setup_component(self.hass, 'sensor', VALID_CONFIG_HOST) - self.assertEqual(len(self.hass.states.all()), 0) + assert len(self.hass.states.all()) == 0 @patch('telnetlib.Telnet', new=TelnetMock) def test_hddtemp_host_unreachable(self): """Test hddtemp if host unreachable.""" assert setup_component(self.hass, 'sensor', VALID_CONFIG_HOST_UNREACHABLE) - self.assertEqual(len(self.hass.states.all()), 0) + assert len(self.hass.states.all()) == 0 diff --git a/tests/components/sensor/test_history_stats.py b/tests/components/sensor/test_history_stats.py index 1a2ec086e..67cacb298 100644 --- a/tests/components/sensor/test_history_stats.py +++ b/tests/components/sensor/test_history_stats.py @@ -12,6 +12,7 @@ from homeassistant.helpers.template import Template import homeassistant.util.dt as dt_util from tests.common import init_recorder_component, get_test_home_assistant +import pytest class TestHistoryStatsSensor(unittest.TestCase): @@ -42,10 +43,10 @@ class TestHistoryStatsSensor(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, 'sensor', config)) + assert setup_component(self.hass, 'sensor', config) state = self.hass.states.get('sensor.test') - self.assertEqual(state.state, STATE_UNKNOWN) + assert state.state == STATE_UNKNOWN def test_period_parsing(self): """Test the conversion from templates to period.""" @@ -64,24 +65,24 @@ class TestHistoryStatsSensor(unittest.TestCase): sensor2_start, sensor2_end = sensor2._period # Start = 00:00:00 - self.assertEqual(sensor1_start.hour, 0) - self.assertEqual(sensor1_start.minute, 0) - self.assertEqual(sensor1_start.second, 0) + assert sensor1_start.hour == 0 + assert sensor1_start.minute == 0 + assert sensor1_start.second == 0 # End = 02:01:00 - self.assertEqual(sensor1_end.hour, 2) - self.assertEqual(sensor1_end.minute, 1) - self.assertEqual(sensor1_end.second, 0) + assert sensor1_end.hour == 2 + assert sensor1_end.minute == 1 + assert sensor1_end.second == 0 # Start = 21:59:00 - self.assertEqual(sensor2_start.hour, 21) - self.assertEqual(sensor2_start.minute, 59) - self.assertEqual(sensor2_start.second, 0) + assert sensor2_start.hour == 21 + assert sensor2_start.minute == 59 + assert sensor2_start.second == 0 # End = 00:00:00 - self.assertEqual(sensor2_end.hour, 0) - self.assertEqual(sensor2_end.minute, 0) - self.assertEqual(sensor2_end.second, 0) + assert sensor2_end.hour == 0 + assert sensor2_end.minute == 0 + assert sensor2_end.second == 0 def test_measure(self): """Test the history statistics sensor measure.""" @@ -119,9 +120,9 @@ class TestHistoryStatsSensor(unittest.TestCase): self.hass, 'binary_sensor.test_id', 'on', start, end, None, 'ratio', 'test') - self.assertEqual(sensor1._type, 'time') - self.assertEqual(sensor3._type, 'count') - self.assertEqual(sensor4._type, 'ratio') + assert sensor1._type == 'time' + assert sensor3._type == 'count' + assert sensor4._type == 'ratio' with patch('homeassistant.components.history.' 'state_changes_during_period', return_value=fake_states): @@ -132,10 +133,10 @@ class TestHistoryStatsSensor(unittest.TestCase): sensor3.update() sensor4.update() - self.assertEqual(sensor1.state, 0.5) - self.assertEqual(sensor2.state, None) - self.assertEqual(sensor3.state, 2) - self.assertEqual(sensor4.state, 50) + assert sensor1.state == 0.5 + assert sensor2.state is None + assert sensor3.state == 2 + assert sensor4.state == 50 def test_wrong_date(self): """Test when start or end value is not a timestamp or a date.""" @@ -153,8 +154,8 @@ class TestHistoryStatsSensor(unittest.TestCase): sensor1.update_period() sensor2.update_period() - self.assertEqual(before_update1, sensor1._period) - self.assertEqual(before_update2, sensor2._period) + assert before_update1 == sensor1._period + assert before_update2 == sensor2._period def test_wrong_duration(self): """Test when duration value is not a timedelta.""" @@ -173,9 +174,9 @@ class TestHistoryStatsSensor(unittest.TestCase): } setup_component(self.hass, 'sensor', config) - self.assertEqual(self.hass.states.get('sensor.test'), None) - self.assertRaises(TypeError, - setup_component(self.hass, 'sensor', config)) + assert self.hass.states.get('sensor.test')is None + with pytest.raises(TypeError): + setup_component(self.hass, 'sensor', config)() def test_bad_template(self): """Test Exception when the template cannot be parsed.""" @@ -193,8 +194,8 @@ class TestHistoryStatsSensor(unittest.TestCase): sensor1.update_period() sensor2.update_period() - self.assertEqual(before_update1, sensor1._period) - self.assertEqual(before_update2, sensor2._period) + assert before_update1 == sensor1._period + assert before_update2 == sensor2._period def test_not_enough_arguments(self): """Test config when not enough arguments provided.""" @@ -212,9 +213,9 @@ class TestHistoryStatsSensor(unittest.TestCase): } setup_component(self.hass, 'sensor', config) - self.assertEqual(self.hass.states.get('sensor.test'), None) - self.assertRaises(TypeError, - setup_component(self.hass, 'sensor', config)) + assert self.hass.states.get('sensor.test')is None + with pytest.raises(TypeError): + setup_component(self.hass, 'sensor', config)() def test_too_many_arguments(self): """Test config when too many arguments provided.""" @@ -234,9 +235,9 @@ class TestHistoryStatsSensor(unittest.TestCase): } setup_component(self.hass, 'sensor', config) - self.assertEqual(self.hass.states.get('sensor.test'), None) - self.assertRaises(TypeError, - setup_component(self.hass, 'sensor', config)) + assert self.hass.states.get('sensor.test')is None + with pytest.raises(TypeError): + setup_component(self.hass, 'sensor', config)() def init_recorder(self): """Initialize the recorder.""" diff --git a/tests/components/sensor/test_imap_email_content.py b/tests/components/sensor/test_imap_email_content.py index a07d94e3d..a0cfb783d 100644 --- a/tests/components/sensor/test_imap_email_content.py +++ b/tests/components/sensor/test_imap_email_content.py @@ -60,14 +60,14 @@ class EmailContentSensor(unittest.TestCase): sensor.entity_id = 'sensor.emailtest' sensor.schedule_update_ha_state(True) self.hass.block_till_done() - self.assertEqual('Test', sensor.state) - self.assertEqual("Test Message", - sensor.device_state_attributes['body']) - self.assertEqual('sender@test.com', - sensor.device_state_attributes['from']) - self.assertEqual('Test', sensor.device_state_attributes['subject']) - self.assertEqual(datetime.datetime(2016, 1, 1, 12, 44, 57), - sensor.device_state_attributes['date']) + assert 'Test' == sensor.state + assert "Test Message" == \ + sensor.device_state_attributes['body'] + assert 'sender@test.com' == \ + sensor.device_state_attributes['from'] + assert 'Test' == sensor.device_state_attributes['subject'] + assert datetime.datetime(2016, 1, 1, 12, 44, 57) == \ + sensor.device_state_attributes['date'] def test_multi_part_with_text(self): """Test multi part emails.""" @@ -91,9 +91,9 @@ class EmailContentSensor(unittest.TestCase): sensor.entity_id = "sensor.emailtest" sensor.schedule_update_ha_state(True) self.hass.block_till_done() - self.assertEqual('Link', sensor.state) - self.assertEqual("Test Message", - sensor.device_state_attributes['body']) + assert 'Link' == sensor.state + assert "Test Message" == \ + sensor.device_state_attributes['body'] def test_multi_part_only_html(self): """Test multi part emails with only HTML.""" @@ -117,10 +117,9 @@ class EmailContentSensor(unittest.TestCase): sensor.entity_id = 'sensor.emailtest' sensor.schedule_update_ha_state(True) self.hass.block_till_done() - self.assertEqual('Link', sensor.state) - self.assertEqual( - "Test Message", - sensor.device_state_attributes['body']) + assert 'Link' == sensor.state + assert "Test Message" == \ + sensor.device_state_attributes['body'] def test_multi_part_only_other_text(self): """Test multi part emails with only other text.""" @@ -141,9 +140,9 @@ class EmailContentSensor(unittest.TestCase): sensor.entity_id = 'sensor.emailtest' sensor.schedule_update_ha_state(True) self.hass.block_till_done() - self.assertEqual('Link', sensor.state) - self.assertEqual("Test Message", - sensor.device_state_attributes['body']) + assert 'Link' == sensor.state + assert "Test Message" == \ + sensor.device_state_attributes['body'] def test_multiple_emails(self): """Test multiple emails.""" @@ -179,11 +178,11 @@ class EmailContentSensor(unittest.TestCase): sensor.schedule_update_ha_state(True) self.hass.block_till_done() - self.assertEqual("Test", states[0].state) - self.assertEqual("Test 2", states[1].state) + assert "Test" == states[0].state + assert "Test 2" == states[1].state - self.assertEqual("Test Message 2", - sensor.device_state_attributes['body']) + assert "Test Message 2" == \ + sensor.device_state_attributes['body'] def test_sender_not_allowed(self): """Test not whitelisted emails.""" @@ -200,7 +199,7 @@ class EmailContentSensor(unittest.TestCase): sensor.entity_id = 'sensor.emailtest' sensor.schedule_update_ha_state(True) self.hass.block_till_done() - self.assertEqual(None, sensor.state) + assert sensor.state is None def test_template(self): """Test value template.""" @@ -219,6 +218,5 @@ class EmailContentSensor(unittest.TestCase): sensor.entity_id = 'sensor.emailtest' sensor.schedule_update_ha_state(True) self.hass.block_till_done() - self.assertEqual( - "Test from sender@test.com with message Test Message", - sensor.state) + assert "Test from sender@test.com with message Test Message" == \ + sensor.state diff --git a/tests/components/sensor/test_jewish_calendar.py b/tests/components/sensor/test_jewish_calendar.py index ba3a11d86..9274ab678 100644 --- a/tests/components/sensor/test_jewish_calendar.py +++ b/tests/components/sensor/test_jewish_calendar.py @@ -71,7 +71,7 @@ class TestJewishCalenderSensor(unittest.TestCase): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop).result() - self.assertEqual(sensor.state, '23 Elul 5778') + assert sensor.state == '23 Elul 5778' def test_jewish_calendar_sensor_date_output_hebrew(self): """Test Jewish calendar sensor date output in hebrew.""" @@ -83,7 +83,7 @@ class TestJewishCalenderSensor(unittest.TestCase): with patch('homeassistant.util.dt.now', return_value=test_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop).result() - self.assertEqual(sensor.state, "כ\"ג באלול ה\' תשע\"ח") + assert sensor.state == "כ\"ג באלול ה\' תשע\"ח" def test_jewish_calendar_sensor_holiday_name(self): """Test Jewish calendar sensor holiday name output in hebrew.""" @@ -95,7 +95,7 @@ class TestJewishCalenderSensor(unittest.TestCase): with patch('homeassistant.util.dt.now', return_value=test_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop).result() - self.assertEqual(sensor.state, "א\' ראש השנה") + assert sensor.state == "א\' ראש השנה" def test_jewish_calendar_sensor_holiday_name_english(self): """Test Jewish calendar sensor holiday name output in english.""" @@ -107,7 +107,7 @@ class TestJewishCalenderSensor(unittest.TestCase): with patch('homeassistant.util.dt.now', return_value=test_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop).result() - self.assertEqual(sensor.state, "Rosh Hashana I") + assert sensor.state == "Rosh Hashana I" def test_jewish_calendar_sensor_holyness(self): """Test Jewish calendar sensor holyness value.""" @@ -119,7 +119,7 @@ class TestJewishCalenderSensor(unittest.TestCase): with patch('homeassistant.util.dt.now', return_value=test_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop).result() - self.assertEqual(sensor.state, 1) + assert sensor.state == 1 def test_jewish_calendar_sensor_torah_reading(self): """Test Jewish calendar sensor torah reading in hebrew.""" @@ -131,7 +131,7 @@ class TestJewishCalenderSensor(unittest.TestCase): with patch('homeassistant.util.dt.now', return_value=test_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop).result() - self.assertEqual(sensor.state, "פרשת נצבים") + assert sensor.state == "פרשת נצבים" def test_jewish_calendar_sensor_first_stars_ny(self): """Test Jewish calendar sensor first stars time in NY, US.""" @@ -143,7 +143,7 @@ class TestJewishCalenderSensor(unittest.TestCase): with patch('homeassistant.util.dt.now', return_value=test_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop).result() - self.assertEqual(sensor.state, time(19, 48)) + assert sensor.state == time(19, 48) def test_jewish_calendar_sensor_first_stars_jerusalem(self): """Test Jewish calendar sensor first stars time in Jerusalem, IL.""" @@ -155,7 +155,7 @@ class TestJewishCalenderSensor(unittest.TestCase): with patch('homeassistant.util.dt.now', return_value=test_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop).result() - self.assertEqual(sensor.state, time(19, 21)) + assert sensor.state == time(19, 21) def test_jewish_calendar_sensor_torah_reading_weekday(self): """Test the sensor showing torah reading also on weekdays.""" @@ -167,4 +167,4 @@ class TestJewishCalenderSensor(unittest.TestCase): with patch('homeassistant.util.dt.now', return_value=test_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop).result() - self.assertEqual(sensor.state, "פרשת לך לך") + assert sensor.state == "פרשת לך לך" diff --git a/tests/components/sensor/test_london_air.py b/tests/components/sensor/test_london_air.py index 56084095b..e6a11b672 100644 --- a/tests/components/sensor/test_london_air.py +++ b/tests/components/sensor/test_london_air.py @@ -31,8 +31,7 @@ class TestLondonAirSensor(unittest.TestCase): def test_setup(self, mock_req): """Test for operational tube_state sensor with proper attributes.""" mock_req.get(URL, text=load_fixture('london_air.json')) - self.assertTrue( - setup_component(self.hass, 'sensor', {'sensor': self.config})) + assert setup_component(self.hass, 'sensor', {'sensor': self.config}) state = self.hass.states.get('sensor.merton') assert state.state == 'Low' diff --git a/tests/components/sensor/test_london_underground.py b/tests/components/sensor/test_london_underground.py index fbffcbd1d..7acd61f64 100644 --- a/tests/components/sensor/test_london_underground.py +++ b/tests/components/sensor/test_london_underground.py @@ -30,8 +30,7 @@ class TestLondonTubeSensor(unittest.TestCase): def test_setup(self, mock_req): """Test for operational tube_state sensor with proper attributes.""" mock_req.get(URL, text=load_fixture('london_underground.json')) - self.assertTrue( - setup_component(self.hass, 'sensor', {'sensor': self.config})) + assert setup_component(self.hass, 'sensor', {'sensor': self.config}) state = self.hass.states.get('sensor.london_overground') assert state.state == 'Minor Delays' diff --git a/tests/components/sensor/test_melissa.py b/tests/components/sensor/test_melissa.py index 7ac90221f..aff3df83c 100644 --- a/tests/components/sensor/test_melissa.py +++ b/tests/components/sensor/test_melissa.py @@ -50,40 +50,40 @@ class TestMelissa(unittest.TestCase): def test_name(self): """Test name property.""" device = self.api.fetch_devices()[self._serial] - self.assertEqual(self.temp.name, '{0} {1}'.format( + assert self.temp.name == '{0} {1}'.format( device['name'], self.temp._type - )) - self.assertEqual(self.hum.name, '{0} {1}'.format( + ) + assert self.hum.name == '{0} {1}'.format( device['name'], self.hum._type - )) + ) def test_state(self): """Test state property.""" device = self.api.status()[self._serial] self.temp.update() - self.assertEqual(self.temp.state, device[self.api.TEMP]) + assert self.temp.state == device[self.api.TEMP] self.hum.update() - self.assertEqual(self.hum.state, device[self.api.HUMIDITY]) + assert self.hum.state == device[self.api.HUMIDITY] def test_unit_of_measurement(self): """Test unit of measurement property.""" - self.assertEqual(self.temp.unit_of_measurement, TEMP_CELSIUS) - self.assertEqual(self.hum.unit_of_measurement, '%') + assert self.temp.unit_of_measurement == TEMP_CELSIUS + assert self.hum.unit_of_measurement == '%' def test_update(self): """Test for update.""" self.temp.update() - self.assertEqual(self.temp.state, 27.4) + assert self.temp.state == 27.4 self.hum.update() - self.assertEqual(self.hum.state, 18.7) + assert self.hum.state == 18.7 def test_update_keyerror(self): """Test for faulty update.""" self.temp._api.status.return_value = {} self.temp.update() - self.assertEqual(None, self.temp.state) + assert self.temp.state is None self.hum._api.status.return_value = {} self.hum.update() - self.assertEqual(None, self.hum.state) + assert self.hum.state is None diff --git a/tests/components/sensor/test_mfi.py b/tests/components/sensor/test_mfi.py index a10246ad7..d30618a33 100644 --- a/tests/components/sensor/test_mfi.py +++ b/tests/components/sensor/test_mfi.py @@ -55,17 +55,15 @@ class TestMfiSensorSetup(unittest.TestCase): from mficlient.client import FailedToLogin mock_client.side_effect = FailedToLogin - self.assertFalse( - self.PLATFORM.setup_platform( - self.hass, dict(self.GOOD_CONFIG), None)) + assert not self.PLATFORM.setup_platform( + self.hass, dict(self.GOOD_CONFIG), None) @mock.patch('mficlient.client.MFiClient') def test_setup_failed_connect(self, mock_client): """Test setup with connection failure.""" mock_client.side_effect = requests.exceptions.ConnectionError - self.assertFalse( - self.PLATFORM.setup_platform( - self.hass, dict(self.GOOD_CONFIG), None)) + assert not self.PLATFORM.setup_platform( + self.hass, dict(self.GOOD_CONFIG), None) @mock.patch('mficlient.client.MFiClient') def test_setup_minimum(self, mock_client): @@ -73,13 +71,11 @@ class TestMfiSensorSetup(unittest.TestCase): config = dict(self.GOOD_CONFIG) del config[self.THING]['port'] assert setup_component(self.hass, self.COMPONENT.DOMAIN, config) - self.assertEqual(mock_client.call_count, 1) - self.assertEqual( - mock_client.call_args, + assert mock_client.call_count == 1 + assert mock_client.call_args == \ mock.call( 'foo', 'user', 'pass', port=6443, use_tls=True, verify=True ) - ) @mock.patch('mficlient.client.MFiClient') def test_setup_with_port(self, mock_client): @@ -87,13 +83,11 @@ class TestMfiSensorSetup(unittest.TestCase): config = dict(self.GOOD_CONFIG) config[self.THING]['port'] = 6123 assert setup_component(self.hass, self.COMPONENT.DOMAIN, config) - self.assertEqual(mock_client.call_count, 1) - self.assertEqual( - mock_client.call_args, + assert mock_client.call_count == 1 + assert mock_client.call_args == \ mock.call( 'foo', 'user', 'pass', port=6123, use_tls=True, verify=True ) - ) @mock.patch('mficlient.client.MFiClient') def test_setup_with_tls_disabled(self, mock_client): @@ -103,13 +97,11 @@ class TestMfiSensorSetup(unittest.TestCase): config[self.THING]['ssl'] = False config[self.THING]['verify_ssl'] = False assert setup_component(self.hass, self.COMPONENT.DOMAIN, config) - self.assertEqual(mock_client.call_count, 1) - self.assertEqual( - mock_client.call_args, + assert mock_client.call_count == 1 + assert mock_client.call_args == \ mock.call( 'foo', 'user', 'pass', port=6080, use_tls=False, verify=False ) - ) @mock.patch('mficlient.client.MFiClient') @mock.patch('homeassistant.components.sensor.mfi.MfiSensor') @@ -142,59 +134,59 @@ class TestMfiSensor(unittest.TestCase): def test_name(self): """Test the name.""" - self.assertEqual(self.port.label, self.sensor.name) + assert self.port.label == self.sensor.name def test_uom_temp(self): """Test the UOM temperature.""" self.port.tag = 'temperature' - self.assertEqual(TEMP_CELSIUS, self.sensor.unit_of_measurement) + assert TEMP_CELSIUS == self.sensor.unit_of_measurement def test_uom_power(self): """Test the UOEM power.""" self.port.tag = 'active_pwr' - self.assertEqual('Watts', self.sensor.unit_of_measurement) + assert 'Watts' == self.sensor.unit_of_measurement def test_uom_digital(self): """Test the UOM digital input.""" self.port.model = 'Input Digital' - self.assertEqual('State', self.sensor.unit_of_measurement) + assert 'State' == self.sensor.unit_of_measurement def test_uom_unknown(self): """Test the UOM.""" self.port.tag = 'balloons' - self.assertEqual('balloons', self.sensor.unit_of_measurement) + assert 'balloons' == self.sensor.unit_of_measurement def test_uom_uninitialized(self): """Test that the UOM defaults if not initialized.""" type(self.port).tag = mock.PropertyMock(side_effect=ValueError) - self.assertEqual('State', self.sensor.unit_of_measurement) + assert 'State' == self.sensor.unit_of_measurement def test_state_digital(self): """Test the digital input.""" self.port.model = 'Input Digital' self.port.value = 0 - self.assertEqual(mfi.STATE_OFF, self.sensor.state) + assert mfi.STATE_OFF == self.sensor.state self.port.value = 1 - self.assertEqual(mfi.STATE_ON, self.sensor.state) + assert mfi.STATE_ON == self.sensor.state self.port.value = 2 - self.assertEqual(mfi.STATE_ON, self.sensor.state) + assert mfi.STATE_ON == self.sensor.state def test_state_digits(self): """Test the state of digits.""" self.port.tag = 'didyoucheckthedict?' self.port.value = 1.25 with mock.patch.dict(mfi.DIGITS, {'didyoucheckthedict?': 1}): - self.assertEqual(1.2, self.sensor.state) + assert 1.2 == self.sensor.state with mock.patch.dict(mfi.DIGITS, {}): - self.assertEqual(1.0, self.sensor.state) + assert 1.0 == self.sensor.state def test_state_uninitialized(self): """Test the state of uninitialized sensors.""" type(self.port).tag = mock.PropertyMock(side_effect=ValueError) - self.assertEqual(mfi.STATE_OFF, self.sensor.state) + assert mfi.STATE_OFF == self.sensor.state def test_update(self): """Test the update.""" self.sensor.update() - self.assertEqual(self.port.refresh.call_count, 1) - self.assertEqual(self.port.refresh.call_args, mock.call()) + assert self.port.refresh.call_count == 1 + assert self.port.refresh.call_args == mock.call() diff --git a/tests/components/sensor/test_mhz19.py b/tests/components/sensor/test_mhz19.py index 421035995..003cc1999 100644 --- a/tests/components/sensor/test_mhz19.py +++ b/tests/components/sensor/test_mhz19.py @@ -31,10 +31,10 @@ class TestMHZ19Sensor(unittest.TestCase): @patch('pmsensor.co2sensor.read_mh_z19', side_effect=OSError('test error')) def test_setup_failed_connect(self, mock_co2): """Test setup when connection error occurs.""" - self.assertFalse(mhz19.setup_platform(self.hass, { + assert not mhz19.setup_platform(self.hass, { 'platform': 'mhz19', mhz19.CONF_SERIAL_DEVICE: 'test.serial', - }, None)) + }, None) def test_setup_connected(self): """Test setup when connection succeeds.""" @@ -43,12 +43,12 @@ class TestMHZ19Sensor(unittest.TestCase): from pmsensor.co2sensor import read_mh_z19_with_temperature read_mh_z19_with_temperature.return_value = None mock_add = Mock() - self.assertTrue(mhz19.setup_platform(self.hass, { + assert mhz19.setup_platform(self.hass, { 'platform': 'mhz19', 'monitored_conditions': ['co2', 'temperature'], mhz19.CONF_SERIAL_DEVICE: 'test.serial', - }, mock_add)) - self.assertEqual(1, mock_add.call_count) + }, mock_add) + assert 1 == mock_add.call_count @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', side_effect=OSError('test error')) @@ -57,7 +57,7 @@ class TestMHZ19Sensor(unittest.TestCase): from pmsensor import co2sensor client = mhz19.MHZClient(co2sensor, 'test.serial') client.update() - self.assertEqual({}, client.data) + assert {} == client.data @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', return_value=(5001, 24)) @@ -66,7 +66,7 @@ class TestMHZ19Sensor(unittest.TestCase): from pmsensor import co2sensor client = mhz19.MHZClient(co2sensor, 'test.serial') client.update() - self.assertIsNone(client.data.get('co2')) + assert client.data.get('co2') is None @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', return_value=(1000, 24)) @@ -75,7 +75,7 @@ class TestMHZ19Sensor(unittest.TestCase): from pmsensor import co2sensor client = mhz19.MHZClient(co2sensor, 'test.serial') client.update() - self.assertEqual({'temperature': 24, 'co2': 1000}, client.data) + assert {'temperature': 24, 'co2': 1000} == client.data @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', return_value=(1000, 24)) @@ -86,11 +86,11 @@ class TestMHZ19Sensor(unittest.TestCase): sensor = mhz19.MHZ19Sensor(client, mhz19.SENSOR_CO2, None, 'name') sensor.update() - self.assertEqual('name: CO2', sensor.name) - self.assertEqual(1000, sensor.state) - self.assertEqual('ppm', sensor.unit_of_measurement) - self.assertTrue(sensor.should_poll) - self.assertEqual({'temperature': 24}, sensor.device_state_attributes) + assert 'name: CO2' == sensor.name + assert 1000 == sensor.state + assert 'ppm' == sensor.unit_of_measurement + assert sensor.should_poll + assert {'temperature': 24} == sensor.device_state_attributes @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', return_value=(1000, 24)) @@ -102,12 +102,11 @@ class TestMHZ19Sensor(unittest.TestCase): client, mhz19.SENSOR_TEMPERATURE, None, 'name') sensor.update() - self.assertEqual('name: Temperature', sensor.name) - self.assertEqual(24, sensor.state) - self.assertEqual('°C', sensor.unit_of_measurement) - self.assertTrue(sensor.should_poll) - self.assertEqual( - {'co2_concentration': 1000}, sensor.device_state_attributes) + assert 'name: Temperature' == sensor.name + assert 24 == sensor.state + assert '°C' == sensor.unit_of_measurement + assert sensor.should_poll + assert {'co2_concentration': 1000} == sensor.device_state_attributes @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', return_value=(1000, 24)) @@ -119,4 +118,4 @@ class TestMHZ19Sensor(unittest.TestCase): client, mhz19.SENSOR_TEMPERATURE, TEMP_FAHRENHEIT, 'name') sensor.update() - self.assertEqual(75.2, sensor.state) + assert 75.2 == sensor.state diff --git a/tests/components/sensor/test_min_max.py b/tests/components/sensor/test_min_max.py index 0376c780e..ae2f40e58 100644 --- a/tests/components/sensor/test_min_max.py +++ b/tests/components/sensor/test_min_max.py @@ -50,9 +50,9 @@ class TestMinMaxSensor(unittest.TestCase): state = self.hass.states.get('sensor.test_min') - self.assertEqual(str(float(self.min)), state.state) - self.assertEqual(self.max, state.attributes.get('max_value')) - self.assertEqual(self.mean, state.attributes.get('mean')) + assert str(float(self.min)) == state.state + assert self.max == state.attributes.get('max_value') + assert self.mean == state.attributes.get('mean') def test_max_sensor(self): """Test the max sensor.""" @@ -79,9 +79,9 @@ class TestMinMaxSensor(unittest.TestCase): state = self.hass.states.get('sensor.test_max') - self.assertEqual(str(float(self.max)), state.state) - self.assertEqual(self.min, state.attributes.get('min_value')) - self.assertEqual(self.mean, state.attributes.get('mean')) + assert str(float(self.max)) == state.state + assert self.min == state.attributes.get('min_value') + assert self.mean == state.attributes.get('mean') def test_mean_sensor(self): """Test the mean sensor.""" @@ -108,9 +108,9 @@ class TestMinMaxSensor(unittest.TestCase): state = self.hass.states.get('sensor.test_mean') - self.assertEqual(str(float(self.mean)), state.state) - self.assertEqual(self.min, state.attributes.get('min_value')) - self.assertEqual(self.max, state.attributes.get('max_value')) + assert str(float(self.mean)) == state.state + assert self.min == state.attributes.get('min_value') + assert self.max == state.attributes.get('max_value') def test_mean_1_digit_sensor(self): """Test the mean with 1-digit precision sensor.""" @@ -138,9 +138,9 @@ class TestMinMaxSensor(unittest.TestCase): state = self.hass.states.get('sensor.test_mean') - self.assertEqual(str(float(self.mean_1_digit)), state.state) - self.assertEqual(self.min, state.attributes.get('min_value')) - self.assertEqual(self.max, state.attributes.get('max_value')) + assert str(float(self.mean_1_digit)) == state.state + assert self.min == state.attributes.get('min_value') + assert self.max == state.attributes.get('max_value') def test_mean_4_digit_sensor(self): """Test the mean with 1-digit precision sensor.""" @@ -168,9 +168,9 @@ class TestMinMaxSensor(unittest.TestCase): state = self.hass.states.get('sensor.test_mean') - self.assertEqual(str(float(self.mean_4_digits)), state.state) - self.assertEqual(self.min, state.attributes.get('min_value')) - self.assertEqual(self.max, state.attributes.get('max_value')) + assert str(float(self.mean_4_digits)) == state.state + assert self.min == state.attributes.get('min_value') + assert self.max == state.attributes.get('max_value') def test_not_enough_sensor_value(self): """Test that there is nothing done if not enough values available.""" @@ -195,25 +195,25 @@ class TestMinMaxSensor(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('sensor.test_max') - self.assertEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN == state.state self.hass.states.set(entity_ids[1], self.values[1]) self.hass.block_till_done() state = self.hass.states.get('sensor.test_max') - self.assertNotEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN != state.state self.hass.states.set(entity_ids[2], STATE_UNKNOWN) self.hass.block_till_done() state = self.hass.states.get('sensor.test_max') - self.assertNotEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN != state.state self.hass.states.set(entity_ids[1], STATE_UNKNOWN) self.hass.block_till_done() state = self.hass.states.get('sensor.test_max') - self.assertEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN == state.state def test_different_unit_of_measurement(self): """Test for different unit of measurement.""" @@ -240,8 +240,8 @@ class TestMinMaxSensor(unittest.TestCase): state = self.hass.states.get('sensor.test') - self.assertEqual(str(float(self.values[0])), state.state) - self.assertEqual('°C', state.attributes.get('unit_of_measurement')) + assert str(float(self.values[0])) == state.state + assert '°C' == state.attributes.get('unit_of_measurement') self.hass.states.set(entity_ids[1], self.values[1], {ATTR_UNIT_OF_MEASUREMENT: TEMP_FAHRENHEIT}) @@ -249,8 +249,8 @@ class TestMinMaxSensor(unittest.TestCase): state = self.hass.states.get('sensor.test') - self.assertEqual(STATE_UNKNOWN, state.state) - self.assertEqual('ERR', state.attributes.get('unit_of_measurement')) + assert STATE_UNKNOWN == state.state + assert 'ERR' == state.attributes.get('unit_of_measurement') self.hass.states.set(entity_ids[2], self.values[2], {ATTR_UNIT_OF_MEASUREMENT: '%'}) @@ -258,8 +258,8 @@ class TestMinMaxSensor(unittest.TestCase): state = self.hass.states.get('sensor.test') - self.assertEqual(STATE_UNKNOWN, state.state) - self.assertEqual('ERR', state.attributes.get('unit_of_measurement')) + assert STATE_UNKNOWN == state.state + assert 'ERR' == state.attributes.get('unit_of_measurement') def test_last_sensor(self): """Test the last sensor.""" @@ -285,8 +285,8 @@ class TestMinMaxSensor(unittest.TestCase): self.hass.states.set(entity_id, value) self.hass.block_till_done() state = self.hass.states.get('sensor.test_last') - self.assertEqual(str(float(value)), state.state) + assert str(float(value)) == state.state - self.assertEqual(self.min, state.attributes.get('min_value')) - self.assertEqual(self.max, state.attributes.get('max_value')) - self.assertEqual(self.mean, state.attributes.get('mean')) + assert self.min == state.attributes.get('min_value') + assert self.max == state.attributes.get('max_value') + assert self.mean == state.attributes.get('mean') diff --git a/tests/components/sensor/test_moldindicator.py b/tests/components/sensor/test_moldindicator.py index 7b2480f12..8b39804ca 100644 --- a/tests/components/sensor/test_moldindicator.py +++ b/tests/components/sensor/test_moldindicator.py @@ -30,7 +30,7 @@ class TestSensorMoldIndicator(unittest.TestCase): def test_setup(self): """Test the mold indicator sensor setup.""" - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { + assert setup_component(self.hass, sensor.DOMAIN, { 'sensor': { 'platform': 'mold_indicator', 'indoor_temp_sensor': 'test.indoortemp', @@ -38,7 +38,7 @@ class TestSensorMoldIndicator(unittest.TestCase): 'indoor_humidity_sensor': 'test.indoorhumidity', 'calibration_factor': 2.0 } - })) + }) moldind = self.hass.states.get('sensor.mold_indicator') assert moldind @@ -53,7 +53,7 @@ class TestSensorMoldIndicator(unittest.TestCase): self.hass.states.set('test.indoorhumidity', '0', {ATTR_UNIT_OF_MEASUREMENT: '%'}) - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { + assert setup_component(self.hass, sensor.DOMAIN, { 'sensor': { 'platform': 'mold_indicator', 'indoor_temp_sensor': 'test.indoortemp', @@ -61,7 +61,7 @@ class TestSensorMoldIndicator(unittest.TestCase): 'indoor_humidity_sensor': 'test.indoorhumidity', 'calibration_factor': 0 } - })) + }) self.hass.start() self.hass.block_till_done() moldind = self.hass.states.get('sensor.mold_indicator') @@ -79,7 +79,7 @@ class TestSensorMoldIndicator(unittest.TestCase): self.hass.states.set('test.indoorhumidity', '-1', {ATTR_UNIT_OF_MEASUREMENT: '%'}) - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { + assert setup_component(self.hass, sensor.DOMAIN, { 'sensor': { 'platform': 'mold_indicator', 'indoor_temp_sensor': 'test.indoortemp', @@ -87,7 +87,7 @@ class TestSensorMoldIndicator(unittest.TestCase): 'indoor_humidity_sensor': 'test.indoorhumidity', 'calibration_factor': 2.0 } - })) + }) self.hass.start() self.hass.block_till_done() @@ -117,7 +117,7 @@ class TestSensorMoldIndicator(unittest.TestCase): def test_calculation(self): """Test the mold indicator internal calculations.""" - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { + assert setup_component(self.hass, sensor.DOMAIN, { 'sensor': { 'platform': 'mold_indicator', 'indoor_temp_sensor': 'test.indoortemp', @@ -125,7 +125,7 @@ class TestSensorMoldIndicator(unittest.TestCase): 'indoor_humidity_sensor': 'test.indoorhumidity', 'calibration_factor': 2.0 } - })) + }) self.hass.start() self.hass.block_till_done() moldind = self.hass.states.get('sensor.mold_indicator') @@ -150,7 +150,7 @@ class TestSensorMoldIndicator(unittest.TestCase): def test_unknown_sensor(self): """Test the sensor_changed function.""" - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { + assert setup_component(self.hass, sensor.DOMAIN, { 'sensor': { 'platform': 'mold_indicator', 'indoor_temp_sensor': 'test.indoortemp', @@ -158,7 +158,7 @@ class TestSensorMoldIndicator(unittest.TestCase): 'indoor_humidity_sensor': 'test.indoorhumidity', 'calibration_factor': 2.0 } - })) + }) self.hass.start() self.hass.states.set('test.indoortemp', STATE_UNKNOWN, @@ -210,7 +210,7 @@ class TestSensorMoldIndicator(unittest.TestCase): def test_sensor_changed(self): """Test the sensor_changed function.""" - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { + assert setup_component(self.hass, sensor.DOMAIN, { 'sensor': { 'platform': 'mold_indicator', 'indoor_temp_sensor': 'test.indoortemp', @@ -218,7 +218,7 @@ class TestSensorMoldIndicator(unittest.TestCase): 'indoor_humidity_sensor': 'test.indoorhumidity', 'calibration_factor': 2.0 } - })) + }) self.hass.start() self.hass.states.set('test.indoortemp', '30', diff --git a/tests/components/sensor/test_moon.py b/tests/components/sensor/test_moon.py index 9086df6e7..14c93678a 100644 --- a/tests/components/sensor/test_moon.py +++ b/tests/components/sensor/test_moon.py @@ -37,7 +37,7 @@ class TestMoonSensor(unittest.TestCase): assert setup_component(self.hass, 'sensor', config) state = self.hass.states.get('sensor.moon_day1') - self.assertEqual(state.state, 'waxing_crescent') + assert state.state == 'waxing_crescent' @patch('homeassistant.components.sensor.moon.dt_util.utcnow', return_value=DAY2) @@ -53,4 +53,4 @@ class TestMoonSensor(unittest.TestCase): assert setup_component(self.hass, 'sensor', config) state = self.hass.states.get('sensor.moon_day2') - self.assertEqual(state.state, 'waning_gibbous') + assert state.state == 'waning_gibbous' diff --git a/tests/components/sensor/test_mqtt.py b/tests/components/sensor/test_mqtt.py index 873de5a9b..15042805a 100644 --- a/tests/components/sensor/test_mqtt.py +++ b/tests/components/sensor/test_mqtt.py @@ -47,9 +47,9 @@ class TestSensorMQTT(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('sensor.test') - self.assertEqual('100', state.state) - self.assertEqual('fav unit', - state.attributes.get('unit_of_measurement')) + assert '100' == state.state + assert 'fav unit' == \ + state.attributes.get('unit_of_measurement') @patch('homeassistant.core.dt_util.utcnow') def test_setting_sensor_value_expires(self, mock_utcnow): @@ -67,7 +67,7 @@ class TestSensorMQTT(unittest.TestCase): }) state = self.hass.states.get('sensor.test') - self.assertEqual('unknown', state.state) + assert 'unknown' == state.state now = datetime(2017, 1, 1, 1, tzinfo=dt_util.UTC) mock_utcnow.return_value = now @@ -76,7 +76,7 @@ class TestSensorMQTT(unittest.TestCase): # Value was set correctly. state = self.hass.states.get('sensor.test') - self.assertEqual('100', state.state) + assert '100' == state.state # Time jump +3s now = now + timedelta(seconds=3) @@ -85,7 +85,7 @@ class TestSensorMQTT(unittest.TestCase): # Value is not yet expired state = self.hass.states.get('sensor.test') - self.assertEqual('100', state.state) + assert '100' == state.state # Next message resets timer mock_utcnow.return_value = now @@ -94,7 +94,7 @@ class TestSensorMQTT(unittest.TestCase): # Value was updated correctly. state = self.hass.states.get('sensor.test') - self.assertEqual('101', state.state) + assert '101' == state.state # Time jump +3s now = now + timedelta(seconds=3) @@ -103,7 +103,7 @@ class TestSensorMQTT(unittest.TestCase): # Value is not yet expired state = self.hass.states.get('sensor.test') - self.assertEqual('101', state.state) + assert '101' == state.state # Time jump +2s now = now + timedelta(seconds=2) @@ -112,7 +112,7 @@ class TestSensorMQTT(unittest.TestCase): # Value is expired now state = self.hass.states.get('sensor.test') - self.assertEqual('unknown', state.state) + assert 'unknown' == state.state def test_setting_sensor_value_via_mqtt_json_message(self): """Test the setting of the value via MQTT with JSON payload.""" @@ -131,7 +131,7 @@ class TestSensorMQTT(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('sensor.test') - self.assertEqual('100', state.state) + assert '100' == state.state def test_force_update_disabled(self): """Test force update option.""" @@ -155,11 +155,11 @@ class TestSensorMQTT(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', '100') self.hass.block_till_done() - self.assertEqual(1, len(events)) + assert 1 == len(events) fire_mqtt_message(self.hass, 'test-topic', '100') self.hass.block_till_done() - self.assertEqual(1, len(events)) + assert 1 == len(events) def test_force_update_enabled(self): """Test force update option.""" @@ -184,41 +184,41 @@ class TestSensorMQTT(unittest.TestCase): fire_mqtt_message(self.hass, 'test-topic', '100') self.hass.block_till_done() - self.assertEqual(1, len(events)) + assert 1 == len(events) fire_mqtt_message(self.hass, 'test-topic', '100') self.hass.block_till_done() - self.assertEqual(2, len(events)) + assert 2 == len(events) def test_default_availability_payload(self): """Test availability by default payload with defined topic.""" - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { + assert setup_component(self.hass, sensor.DOMAIN, { sensor.DOMAIN: { 'platform': 'mqtt', 'name': 'test', 'state_topic': 'test-topic', 'availability_topic': 'availability-topic' } - })) + }) state = self.hass.states.get('sensor.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'online') self.hass.block_till_done() state = self.hass.states.get('sensor.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'offline') self.hass.block_till_done() state = self.hass.states.get('sensor.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def test_custom_availability_payload(self): """Test availability by custom payload with defined topic.""" - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { + assert setup_component(self.hass, sensor.DOMAIN, { sensor.DOMAIN: { 'platform': 'mqtt', 'name': 'test', @@ -227,22 +227,22 @@ class TestSensorMQTT(unittest.TestCase): 'payload_available': 'good', 'payload_not_available': 'nogood' } - })) + }) state = self.hass.states.get('sensor.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'good') self.hass.block_till_done() state = self.hass.states.get('sensor.test') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'nogood') self.hass.block_till_done() state = self.hass.states.get('sensor.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def _send_time_changed(self, now): """Send a time changed event.""" @@ -265,8 +265,8 @@ class TestSensorMQTT(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('sensor.test') - self.assertEqual('100', - state.attributes.get('val')) + assert '100' == \ + state.attributes.get('val') @patch('homeassistant.components.sensor.mqtt._LOGGER') def test_update_with_json_attrs_not_dict(self, mock_logger): @@ -286,9 +286,8 @@ class TestSensorMQTT(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('sensor.test') - self.assertEqual(None, - state.attributes.get('val')) - self.assertTrue(mock_logger.warning.called) + assert state.attributes.get('val') is None + assert mock_logger.warning.called @patch('homeassistant.components.sensor.mqtt._LOGGER') def test_update_with_json_attrs_bad_JSON(self, mock_logger): @@ -308,10 +307,9 @@ class TestSensorMQTT(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('sensor.test') - self.assertEqual(None, - state.attributes.get('val')) - self.assertTrue(mock_logger.warning.called) - self.assertTrue(mock_logger.debug.called) + assert state.attributes.get('val') is None + assert mock_logger.warning.called + assert mock_logger.debug.called def test_update_with_json_attrs_and_template(self): """Test attributes get extracted from a JSON result.""" @@ -331,9 +329,9 @@ class TestSensorMQTT(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('sensor.test') - self.assertEqual('100', - state.attributes.get('val')) - self.assertEqual('100', state.state) + assert '100' == \ + state.attributes.get('val') + assert '100' == state.state def test_invalid_device_class(self): """Test device_class option with invalid value.""" diff --git a/tests/components/sensor/test_mqtt_room.py b/tests/components/sensor/test_mqtt_room.py index 88fa611b2..74852abff 100644 --- a/tests/components/sensor/test_mqtt_room.py +++ b/tests/components/sensor/test_mqtt_room.py @@ -53,7 +53,7 @@ class TestMQTTRoomSensor(unittest.TestCase): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() mock_mqtt_component(self.hass) - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { + assert setup_component(self.hass, sensor.DOMAIN, { sensor.DOMAIN: { CONF_PLATFORM: 'mqtt_room', CONF_NAME: NAME, @@ -61,7 +61,7 @@ class TestMQTTRoomSensor(unittest.TestCase): CONF_STATE_TOPIC: 'room_presence', CONF_QOS: DEFAULT_QOS, CONF_TIMEOUT: 5 - }})) + }}) # Clear state between tests self.hass.states.set(SENSOR_STATE, None) @@ -79,12 +79,12 @@ class TestMQTTRoomSensor(unittest.TestCase): def assert_state(self, room): """Test the assertion of a room state.""" state = self.hass.states.get(SENSOR_STATE) - self.assertEqual(state.state, room) + assert state.state == room def assert_distance(self, distance): """Test the assertion of a distance state.""" state = self.hass.states.get(SENSOR_STATE) - self.assertEqual(state.attributes.get('distance'), distance) + assert state.attributes.get('distance') == distance def test_room_update(self): """Test the updating between rooms.""" diff --git a/tests/components/sensor/test_nsw_fuel_station.py b/tests/components/sensor/test_nsw_fuel_station.py index 1ee314d9e..aa5c2fbe5 100644 --- a/tests/components/sensor/test_nsw_fuel_station.py +++ b/tests/components/sensor/test_nsw_fuel_station.py @@ -92,8 +92,8 @@ class TestNSWFuelStation(unittest.TestCase): def test_setup(self, mock_nsw_fuel): """Test the setup with custom settings.""" with assert_setup_component(1, sensor.DOMAIN): - self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { - 'sensor': VALID_CONFIG})) + assert setup_component(self.hass, sensor.DOMAIN, { + 'sensor': VALID_CONFIG}) fake_entities = [ 'my_fake_station_p95', @@ -102,16 +102,16 @@ class TestNSWFuelStation(unittest.TestCase): for entity_id in fake_entities: state = self.hass.states.get('sensor.{}'.format(entity_id)) - self.assertIsNotNone(state) + assert state is not None @MockDependency('nsw_fuel') @patch('nsw_fuel.FuelCheckClient', new=FuelCheckClientMock) def test_sensor_values(self, mock_nsw_fuel): """Test retrieval of sensor values.""" - self.assertTrue(setup_component( - self.hass, sensor.DOMAIN, {'sensor': VALID_CONFIG})) + assert setup_component( + self.hass, sensor.DOMAIN, {'sensor': VALID_CONFIG}) - self.assertEqual('140.0', self.hass.states.get( - 'sensor.my_fake_station_e10').state) - self.assertEqual('150.0', self.hass.states.get( - 'sensor.my_fake_station_p95').state) + assert '140.0' == self.hass.states.get( + 'sensor.my_fake_station_e10').state + assert '150.0' == self.hass.states.get( + 'sensor.my_fake_station_p95').state diff --git a/tests/components/sensor/test_openhardwaremonitor.py b/tests/components/sensor/test_openhardwaremonitor.py index f66b6dcb3..5117f87cd 100644 --- a/tests/components/sensor/test_openhardwaremonitor.py +++ b/tests/components/sensor/test_openhardwaremonitor.py @@ -29,12 +29,12 @@ class TestOpenHardwareMonitorSetup(unittest.TestCase): mock_req.get('http://localhost:8085/data.json', text=load_fixture('openhardwaremonitor.json')) - self.assertTrue(setup_component(self.hass, 'sensor', self.config)) + assert setup_component(self.hass, 'sensor', self.config) entities = self.hass.states.async_entity_ids('sensor') - self.assertEqual(len(entities), 38) + assert len(entities) == 38 state = self.hass.states.get( 'sensor.testpc_intel_core_i77700_clocks_bus_speed') - self.assertIsNot(state, None) - self.assertEqual(state.state, '100') + assert state is not None + assert state.state == '100' diff --git a/tests/components/sensor/test_radarr.py b/tests/components/sensor/test_radarr.py index 30195b73a..5ac23f762 100644 --- a/tests/components/sensor/test_radarr.py +++ b/tests/components/sensor/test_radarr.py @@ -224,14 +224,12 @@ class TestRadarrSetup(unittest.TestCase): radarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual('263.10', device.state) - self.assertEqual('mdi:harddisk', device.icon) - self.assertEqual('GB', device.unit_of_measurement) - self.assertEqual('Radarr Disk Space', device.name) - self.assertEqual( - '263.10/465.42GB (56.53%)', + assert '263.10' == device.state + assert 'mdi:harddisk' == device.icon + assert 'GB' == device.unit_of_measurement + assert 'Radarr Disk Space' == device.name + assert '263.10/465.42GB (56.53%)' == \ device.device_state_attributes["/data"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_diskspace_paths(self, req_mock): @@ -251,14 +249,12 @@ class TestRadarrSetup(unittest.TestCase): radarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual('263.10', device.state) - self.assertEqual('mdi:harddisk', device.icon) - self.assertEqual('GB', device.unit_of_measurement) - self.assertEqual('Radarr Disk Space', device.name) - self.assertEqual( - '263.10/465.42GB (56.53%)', + assert '263.10' == device.state + assert 'mdi:harddisk' == device.icon + assert 'GB' == device.unit_of_measurement + assert 'Radarr Disk Space' == device.name + assert '263.10/465.42GB (56.53%)' == \ device.device_state_attributes["/data"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_commands(self, req_mock): @@ -278,14 +274,12 @@ class TestRadarrSetup(unittest.TestCase): radarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('mdi:code-braces', device.icon) - self.assertEqual('Commands', device.unit_of_measurement) - self.assertEqual('Radarr Commands', device.name) - self.assertEqual( - 'pending', + assert 1 == device.state + assert 'mdi:code-braces' == device.icon + assert 'Commands' == device.unit_of_measurement + assert 'Radarr Commands' == device.name + assert 'pending' == \ device.device_state_attributes["RescanMovie"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_movies(self, req_mock): @@ -305,14 +299,12 @@ class TestRadarrSetup(unittest.TestCase): radarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('mdi:television', device.icon) - self.assertEqual('Movies', device.unit_of_measurement) - self.assertEqual('Radarr Movies', device.name) - self.assertEqual( - 'false', + assert 1 == device.state + assert 'mdi:television' == device.icon + assert 'Movies' == device.unit_of_measurement + assert 'Radarr Movies' == device.name + assert 'false' == \ device.device_state_attributes["Assassin's Creed (2016)"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_upcoming_multiple_days(self, req_mock): @@ -332,14 +324,12 @@ class TestRadarrSetup(unittest.TestCase): radarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('mdi:television', device.icon) - self.assertEqual('Movies', device.unit_of_measurement) - self.assertEqual('Radarr Upcoming', device.name) - self.assertEqual( - '2017-01-27T00:00:00Z', + assert 1 == device.state + assert 'mdi:television' == device.icon + assert 'Movies' == device.unit_of_measurement + assert 'Radarr Upcoming' == device.name + assert '2017-01-27T00:00:00Z' == \ device.device_state_attributes["Resident Evil (2017)"] - ) @pytest.mark.skip @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) @@ -363,14 +353,12 @@ class TestRadarrSetup(unittest.TestCase): radarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('mdi:television', device.icon) - self.assertEqual('Movies', device.unit_of_measurement) - self.assertEqual('Radarr Upcoming', device.name) - self.assertEqual( - '2017-01-27T00:00:00Z', + assert 1 == device.state + assert 'mdi:television' == device.icon + assert 'Movies' == device.unit_of_measurement + assert 'Radarr Upcoming' == device.name + assert '2017-01-27T00:00:00Z' == \ device.device_state_attributes["Resident Evil (2017)"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_system_status(self, req_mock): @@ -390,11 +378,10 @@ class TestRadarrSetup(unittest.TestCase): radarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual('0.2.0.210', device.state) - self.assertEqual('mdi:information', device.icon) - self.assertEqual('Radarr Status', device.name) - self.assertEqual( - '4.8.13.1', device.device_state_attributes['osVersion']) + assert '0.2.0.210' == device.state + assert 'mdi:information' == device.icon + assert 'Radarr Status' == device.name + assert '4.8.13.1' == device.device_state_attributes['osVersion'] @pytest.mark.skip @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) @@ -416,15 +403,13 @@ class TestRadarrSetup(unittest.TestCase): radarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('s', device.ssl) - self.assertEqual('mdi:television', device.icon) - self.assertEqual('Movies', device.unit_of_measurement) - self.assertEqual('Radarr Upcoming', device.name) - self.assertEqual( - '2017-01-27T00:00:00Z', + assert 1 == device.state + assert 's' == device.ssl + assert 'mdi:television' == device.icon + assert 'Movies' == device.unit_of_measurement + assert 'Radarr Upcoming' == device.name + assert '2017-01-27T00:00:00Z' == \ device.device_state_attributes["Resident Evil (2017)"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_exception) def test_exception_handling(self, req_mock): @@ -444,4 +429,4 @@ class TestRadarrSetup(unittest.TestCase): radarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(None, device.state) + assert device.state is None diff --git a/tests/components/sensor/test_random.py b/tests/components/sensor/test_random.py index e04fc31af..81f7a18f4 100644 --- a/tests/components/sensor/test_random.py +++ b/tests/components/sensor/test_random.py @@ -32,5 +32,5 @@ class TestRandomSensor(unittest.TestCase): state = self.hass.states.get('sensor.test') - self.assertLessEqual(int(state.state), config['sensor']['maximum']) - self.assertGreaterEqual(int(state.state), config['sensor']['minimum']) + assert int(state.state) <= config['sensor']['maximum'] + assert int(state.state) >= config['sensor']['minimum'] diff --git a/tests/components/sensor/test_rest.py b/tests/components/sensor/test_rest.py index 7f818193a..2ce72fc4f 100644 --- a/tests/components/sensor/test_rest.py +++ b/tests/components/sensor/test_rest.py @@ -15,6 +15,7 @@ from homeassistant.const import STATE_UNKNOWN from homeassistant.helpers.config_validation import template from tests.common import get_test_home_assistant, assert_setup_component +import pytest class TestRestSensorSetup(unittest.TestCase): @@ -36,7 +37,7 @@ class TestRestSensorSetup(unittest.TestCase): def test_setup_missing_schema(self): """Test setup with resource missing schema.""" - with self.assertRaises(MissingSchema): + with pytest.raises(MissingSchema): rest.setup_platform(self.hass, { 'platform': 'rest', 'resource': 'localhost', @@ -67,20 +68,20 @@ class TestRestSensorSetup(unittest.TestCase): """Test setup with minimum configuration.""" mock_req.get('http://localhost', status_code=200) with assert_setup_component(1, 'sensor'): - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': { 'platform': 'rest', 'resource': 'http://localhost' } - })) - self.assertEqual(2, mock_req.call_count) + }) + assert 2 == mock_req.call_count @requests_mock.Mocker() def test_setup_get(self, mock_req): """Test setup with valid configuration.""" mock_req.get('http://localhost', status_code=200) with assert_setup_component(1, 'sensor'): - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': { 'platform': 'rest', 'resource': 'http://localhost', @@ -94,15 +95,15 @@ class TestRestSensorSetup(unittest.TestCase): 'password': 'my password', 'headers': {'Accept': 'application/json'} } - })) - self.assertEqual(2, mock_req.call_count) + }) + assert 2 == mock_req.call_count @requests_mock.Mocker() def test_setup_post(self, mock_req): """Test setup with valid configuration.""" mock_req.post('http://localhost', status_code=200) with assert_setup_component(1, 'sensor'): - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': { 'platform': 'rest', 'resource': 'http://localhost', @@ -117,8 +118,8 @@ class TestRestSensorSetup(unittest.TestCase): 'password': 'my password', 'headers': {'Accept': 'application/json'} } - })) - self.assertEqual(2, mock_req.call_count) + }) + assert 2 == mock_req.call_count class TestRestSensor(unittest.TestCase): @@ -153,30 +154,28 @@ class TestRestSensor(unittest.TestCase): def test_name(self): """Test the name.""" - self.assertEqual(self.name, self.sensor.name) + assert self.name == self.sensor.name def test_unit_of_measurement(self): """Test the unit of measurement.""" - self.assertEqual( - self.unit_of_measurement, self.sensor.unit_of_measurement) + assert self.unit_of_measurement == self.sensor.unit_of_measurement def test_force_update(self): """Test the unit of measurement.""" - self.assertEqual( - self.force_update, self.sensor.force_update) + assert self.force_update == self.sensor.force_update def test_state(self): """Test the initial state.""" self.sensor.update() - self.assertEqual(self.initial_state, self.sensor.state) + assert self.initial_state == self.sensor.state def test_update_when_value_is_none(self): """Test state gets updated to unknown when sensor returns no data.""" self.rest.update = Mock( 'rest.RestData.update', side_effect=self.update_side_effect(None)) self.sensor.update() - self.assertEqual(STATE_UNKNOWN, self.sensor.state) - self.assertFalse(self.sensor.available) + assert STATE_UNKNOWN == self.sensor.state + assert not self.sensor.available def test_update_when_value_changed(self): """Test state gets updated when sensor returns a new status.""" @@ -184,8 +183,8 @@ class TestRestSensor(unittest.TestCase): side_effect=self.update_side_effect( '{ "key": "updated_state" }')) self.sensor.update() - self.assertEqual('updated_state', self.sensor.state) - self.assertTrue(self.sensor.available) + assert 'updated_state' == self.sensor.state + assert self.sensor.available def test_update_with_no_template(self): """Test update when there is no value template.""" @@ -196,8 +195,8 @@ class TestRestSensor(unittest.TestCase): self.unit_of_measurement, None, [], self.force_update) self.sensor.update() - self.assertEqual('plain_state', self.sensor.state) - self.assertTrue(self.sensor.available) + assert 'plain_state' == self.sensor.state + assert self.sensor.available def test_update_with_json_attrs(self): """Test attributes get extracted from a JSON result.""" @@ -208,8 +207,8 @@ class TestRestSensor(unittest.TestCase): self.unit_of_measurement, None, ['key'], self.force_update) self.sensor.update() - self.assertEqual('some_json_value', - self.sensor.device_state_attributes['key']) + assert 'some_json_value' == \ + self.sensor.device_state_attributes['key'] @patch('homeassistant.components.sensor.rest._LOGGER') def test_update_with_json_attrs_no_data(self, mock_logger): @@ -220,8 +219,8 @@ class TestRestSensor(unittest.TestCase): self.unit_of_measurement, None, ['key'], self.force_update) self.sensor.update() - self.assertEqual({}, self.sensor.device_state_attributes) - self.assertTrue(mock_logger.warning.called) + assert {} == self.sensor.device_state_attributes + assert mock_logger.warning.called @patch('homeassistant.components.sensor.rest._LOGGER') def test_update_with_json_attrs_not_dict(self, mock_logger): @@ -233,8 +232,8 @@ class TestRestSensor(unittest.TestCase): self.unit_of_measurement, None, ['key'], self.force_update) self.sensor.update() - self.assertEqual({}, self.sensor.device_state_attributes) - self.assertTrue(mock_logger.warning.called) + assert {} == self.sensor.device_state_attributes + assert mock_logger.warning.called @patch('homeassistant.components.sensor.rest._LOGGER') def test_update_with_json_attrs_bad_JSON(self, mock_logger): @@ -246,9 +245,9 @@ class TestRestSensor(unittest.TestCase): self.unit_of_measurement, None, ['key'], self.force_update) self.sensor.update() - self.assertEqual({}, self.sensor.device_state_attributes) - self.assertTrue(mock_logger.warning.called) - self.assertTrue(mock_logger.debug.called) + assert {} == self.sensor.device_state_attributes + assert mock_logger.warning.called + assert mock_logger.debug.called def test_update_with_json_attrs_and_template(self): """Test attributes get extracted from a JSON result.""" @@ -261,10 +260,10 @@ class TestRestSensor(unittest.TestCase): self.force_update) self.sensor.update() - self.assertEqual('json_state_updated_value', self.sensor.state) - self.assertEqual('json_state_updated_value', - self.sensor.device_state_attributes['key'], - self.force_update) + assert 'json_state_updated_value' == self.sensor.state + assert 'json_state_updated_value' == \ + self.sensor.device_state_attributes['key'], \ + self.force_update class TestRestData(unittest.TestCase): @@ -283,10 +282,10 @@ class TestRestData(unittest.TestCase): """Test update.""" mock_req.get('http://localhost', text='test data') self.rest.update() - self.assertEqual('test data', self.rest.data) + assert 'test data' == self.rest.data @patch('requests.Session', side_effect=RequestException) def test_update_request_exception(self, mock_req): """Test update when a request exception occurs.""" self.rest.update() - self.assertEqual(None, self.rest.data) + assert self.rest.data is None diff --git a/tests/components/sensor/test_rfxtrx.py b/tests/components/sensor/test_rfxtrx.py index 3f577127a..653a17e41 100644 --- a/tests/components/sensor/test_rfxtrx.py +++ b/tests/components/sensor/test_rfxtrx.py @@ -29,66 +29,66 @@ class TestSensorRfxtrx(unittest.TestCase): def test_default_config(self): """Test with 0 sensor.""" - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'devices': - {}}})) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + {}}}) + assert 0 == len(rfxtrx_core.RFX_DEVICES) def test_old_config_sensor(self): """Test with 1 sensor.""" - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'devices': {'sensor_0502': { 'name': 'Test', 'packetid': '0a52080705020095220269', - 'data_type': 'Temperature'}}}})) + 'data_type': 'Temperature'}}}}) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) entity = rfxtrx_core.RFX_DEVICES['sensor_0502']['Temperature'] - self.assertEqual('Test', entity.name) - self.assertEqual(TEMP_CELSIUS, entity.unit_of_measurement) - self.assertEqual(None, entity.state) + assert 'Test' == entity.name + assert TEMP_CELSIUS == entity.unit_of_measurement + assert entity.state is None def test_one_sensor(self): """Test with 1 sensor.""" - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'devices': {'0a52080705020095220269': { 'name': 'Test', - 'data_type': 'Temperature'}}}})) + 'data_type': 'Temperature'}}}}) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) entity = rfxtrx_core.RFX_DEVICES['sensor_0502']['Temperature'] - self.assertEqual('Test', entity.name) - self.assertEqual(TEMP_CELSIUS, entity.unit_of_measurement) - self.assertEqual(None, entity.state) + assert 'Test' == entity.name + assert TEMP_CELSIUS == entity.unit_of_measurement + assert entity.state is None def test_one_sensor_no_datatype(self): """Test with 1 sensor.""" - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'devices': {'0a52080705020095220269': { - 'name': 'Test'}}}})) + 'name': 'Test'}}}}) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) entity = rfxtrx_core.RFX_DEVICES['sensor_0502']['Temperature'] - self.assertEqual('Test', entity.name) - self.assertEqual(TEMP_CELSIUS, entity.unit_of_measurement) - self.assertEqual(None, entity.state) + assert 'Test' == entity.name + assert TEMP_CELSIUS == entity.unit_of_measurement + assert entity.state is None entity_id = rfxtrx_core.RFX_DEVICES['sensor_0502']['Temperature']\ .entity_id entity = self.hass.states.get(entity_id) - self.assertEqual('Test', entity.name) - self.assertEqual('unknown', entity.state) + assert 'Test' == entity.name + assert 'unknown' == entity.state def test_several_sensors(self): """Test with 3 sensors.""" - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'devices': {'0a52080705020095220269': { @@ -97,119 +97,119 @@ class TestSensorRfxtrx(unittest.TestCase): '0a520802060100ff0e0269': { 'name': 'Bath', 'data_type': ['Temperature', 'Humidity'] - }}}})) + }}}}) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) device_num = 0 for id in rfxtrx_core.RFX_DEVICES: if id == 'sensor_0601': device_num = device_num + 1 - self.assertEqual(len(rfxtrx_core.RFX_DEVICES[id]), 2) + assert len(rfxtrx_core.RFX_DEVICES[id]) == 2 _entity_temp = rfxtrx_core.RFX_DEVICES[id]['Temperature'] _entity_hum = rfxtrx_core.RFX_DEVICES[id]['Humidity'] - self.assertEqual('%', _entity_hum.unit_of_measurement) - self.assertEqual('Bath', _entity_hum.__str__()) - self.assertEqual(None, _entity_hum.state) - self.assertEqual(TEMP_CELSIUS, - _entity_temp.unit_of_measurement) - self.assertEqual('Bath', _entity_temp.__str__()) + assert '%' == _entity_hum.unit_of_measurement + assert 'Bath' == _entity_hum.__str__() + assert _entity_hum.state is None + assert TEMP_CELSIUS == \ + _entity_temp.unit_of_measurement + assert 'Bath' == _entity_temp.__str__() elif id == 'sensor_0502': device_num = device_num + 1 entity = rfxtrx_core.RFX_DEVICES[id]['Temperature'] - self.assertEqual(None, entity.state) - self.assertEqual(TEMP_CELSIUS, entity.unit_of_measurement) - self.assertEqual('Test', entity.__str__()) + assert entity.state is None + assert TEMP_CELSIUS == entity.unit_of_measurement + assert 'Test' == entity.__str__() - self.assertEqual(2, device_num) + assert 2 == device_num def test_discover_sensor(self): """Test with discovery of sensor.""" - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'automatic_add': True, - 'devices': {}}})) + 'devices': {}}}) event = rfxtrx_core.get_rfx_object('0a520801070100b81b0279') event.data = bytearray(b'\nR\x08\x01\x07\x01\x00\xb8\x1b\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) entity = rfxtrx_core.RFX_DEVICES['sensor_0701']['Temperature'] - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) - self.assertEqual({'Humidity status': 'normal', - 'Temperature': 18.4, - 'Rssi numeric': 7, 'Humidity': 27, - 'Battery numeric': 9, - 'Humidity status numeric': 2}, - entity.device_state_attributes) - self.assertEqual('0a520801070100b81b0279', - entity.__str__()) + assert 1 == len(rfxtrx_core.RFX_DEVICES) + assert {'Humidity status': 'normal', + 'Temperature': 18.4, + 'Rssi numeric': 7, 'Humidity': 27, + 'Battery numeric': 9, + 'Humidity status numeric': 2} == \ + entity.device_state_attributes + assert '0a520801070100b81b0279' == \ + entity.__str__() rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) event = rfxtrx_core.get_rfx_object('0a52080405020095240279') event.data = bytearray(b'\nR\x08\x04\x05\x02\x00\x95$\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) entity = rfxtrx_core.RFX_DEVICES['sensor_0502']['Temperature'] - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) - self.assertEqual({'Humidity status': 'normal', - 'Temperature': 14.9, - 'Rssi numeric': 7, 'Humidity': 36, - 'Battery numeric': 9, - 'Humidity status numeric': 2}, - entity.device_state_attributes) - self.assertEqual('0a52080405020095240279', - entity.__str__()) + assert 2 == len(rfxtrx_core.RFX_DEVICES) + assert {'Humidity status': 'normal', + 'Temperature': 14.9, + 'Rssi numeric': 7, 'Humidity': 36, + 'Battery numeric': 9, + 'Humidity status numeric': 2} == \ + entity.device_state_attributes + assert '0a52080405020095240279' == \ + entity.__str__() event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray(b'\nR\x08^\x07\x01\x00\xb3\x1b\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) entity = rfxtrx_core.RFX_DEVICES['sensor_0701']['Temperature'] - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) - self.assertEqual({'Humidity status': 'normal', - 'Temperature': 17.9, - 'Rssi numeric': 7, 'Humidity': 27, - 'Battery numeric': 9, - 'Humidity status numeric': 2}, - entity.device_state_attributes) - self.assertEqual('0a520801070100b81b0279', - entity.__str__()) + assert 2 == len(rfxtrx_core.RFX_DEVICES) + assert {'Humidity status': 'normal', + 'Temperature': 17.9, + 'Rssi numeric': 7, 'Humidity': 27, + 'Battery numeric': 9, + 'Humidity status numeric': 2} == \ + entity.device_state_attributes + assert '0a520801070100b81b0279' == \ + entity.__str__() # trying to add a switch event = rfxtrx_core.get_rfx_object('0b1100cd0213c7f210010f70') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) def test_discover_sensor_noautoadd(self): """Test with discover of sensor when auto add is False.""" - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'automatic_add': False, - 'devices': {}}})) + 'devices': {}}}) event = rfxtrx_core.get_rfx_object('0a520801070100b81b0279') event.data = bytearray(b'\nR\x08\x01\x07\x01\x00\xb8\x1b\x02y') - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) event = rfxtrx_core.get_rfx_object('0a52080405020095240279') event.data = bytearray(b'\nR\x08\x04\x05\x02\x00\x95$\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray(b'\nR\x08^\x07\x01\x00\xb3\x1b\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) def test_update_of_sensors(self): """Test with 3 sensors.""" - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'devices': {'0a52080705020095220269': { @@ -218,30 +218,30 @@ class TestSensorRfxtrx(unittest.TestCase): '0a520802060100ff0e0269': { 'name': 'Bath', 'data_type': ['Temperature', 'Humidity'] - }}}})) + }}}}) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) device_num = 0 for id in rfxtrx_core.RFX_DEVICES: if id == 'sensor_0601': device_num = device_num + 1 - self.assertEqual(len(rfxtrx_core.RFX_DEVICES[id]), 2) + assert len(rfxtrx_core.RFX_DEVICES[id]) == 2 _entity_temp = rfxtrx_core.RFX_DEVICES[id]['Temperature'] _entity_hum = rfxtrx_core.RFX_DEVICES[id]['Humidity'] - self.assertEqual('%', _entity_hum.unit_of_measurement) - self.assertEqual('Bath', _entity_hum.__str__()) - self.assertEqual(None, _entity_temp.state) - self.assertEqual(TEMP_CELSIUS, - _entity_temp.unit_of_measurement) - self.assertEqual('Bath', _entity_temp.__str__()) + assert '%' == _entity_hum.unit_of_measurement + assert 'Bath' == _entity_hum.__str__() + assert _entity_temp.state is None + assert TEMP_CELSIUS == \ + _entity_temp.unit_of_measurement + assert 'Bath' == _entity_temp.__str__() elif id == 'sensor_0502': device_num = device_num + 1 entity = rfxtrx_core.RFX_DEVICES[id]['Temperature'] - self.assertEqual(None, entity.state) - self.assertEqual(TEMP_CELSIUS, entity.unit_of_measurement) - self.assertEqual('Test', entity.__str__()) + assert entity.state is None + assert TEMP_CELSIUS == entity.unit_of_measurement + assert 'Test' == entity.__str__() - self.assertEqual(2, device_num) + assert 2 == device_num event = rfxtrx_core.get_rfx_object('0a520802060101ff0f0269') event.data = bytearray(b'\nR\x08\x01\x07\x01\x00\xb8\x1b\x02y') @@ -252,45 +252,45 @@ class TestSensorRfxtrx(unittest.TestCase): event.data = bytearray(b'\nR\x08\x04\x05\x02\x00\x95$\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) device_num = 0 for id in rfxtrx_core.RFX_DEVICES: if id == 'sensor_0601': device_num = device_num + 1 - self.assertEqual(len(rfxtrx_core.RFX_DEVICES[id]), 2) + assert len(rfxtrx_core.RFX_DEVICES[id]) == 2 _entity_temp = rfxtrx_core.RFX_DEVICES[id]['Temperature'] _entity_hum = rfxtrx_core.RFX_DEVICES[id]['Humidity'] - self.assertEqual('%', _entity_hum.unit_of_measurement) - self.assertEqual(15, _entity_hum.state) - self.assertEqual({'Battery numeric': 9, 'Temperature': 51.1, - 'Humidity': 15, 'Humidity status': 'normal', - 'Humidity status numeric': 2, - 'Rssi numeric': 6}, - _entity_hum.device_state_attributes) - self.assertEqual('Bath', _entity_hum.__str__()) + assert '%' == _entity_hum.unit_of_measurement + assert 15 == _entity_hum.state + assert {'Battery numeric': 9, 'Temperature': 51.1, + 'Humidity': 15, 'Humidity status': 'normal', + 'Humidity status numeric': 2, + 'Rssi numeric': 6} == \ + _entity_hum.device_state_attributes + assert 'Bath' == _entity_hum.__str__() - self.assertEqual(TEMP_CELSIUS, - _entity_temp.unit_of_measurement) - self.assertEqual(51.1, _entity_temp.state) - self.assertEqual({'Battery numeric': 9, 'Temperature': 51.1, - 'Humidity': 15, 'Humidity status': 'normal', - 'Humidity status numeric': 2, - 'Rssi numeric': 6}, - _entity_temp.device_state_attributes) - self.assertEqual('Bath', _entity_temp.__str__()) + assert TEMP_CELSIUS == \ + _entity_temp.unit_of_measurement + assert 51.1 == _entity_temp.state + assert {'Battery numeric': 9, 'Temperature': 51.1, + 'Humidity': 15, 'Humidity status': 'normal', + 'Humidity status numeric': 2, + 'Rssi numeric': 6} == \ + _entity_temp.device_state_attributes + assert 'Bath' == _entity_temp.__str__() elif id == 'sensor_0502': device_num = device_num + 1 entity = rfxtrx_core.RFX_DEVICES[id]['Temperature'] - self.assertEqual(TEMP_CELSIUS, entity.unit_of_measurement) - self.assertEqual(13.3, entity.state) - self.assertEqual({'Humidity status': 'normal', - 'Temperature': 13.3, - 'Rssi numeric': 6, 'Humidity': 34, - 'Battery numeric': 9, - 'Humidity status numeric': 2}, - entity.device_state_attributes) - self.assertEqual('Test', entity.__str__()) + assert TEMP_CELSIUS == entity.unit_of_measurement + assert 13.3 == entity.state + assert {'Humidity status': 'normal', + 'Temperature': 13.3, + 'Rssi numeric': 6, 'Humidity': 34, + 'Battery numeric': 9, + 'Humidity status numeric': 2} == \ + entity.device_state_attributes + assert 'Test' == entity.__str__() - self.assertEqual(2, device_num) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == device_num + assert 2 == len(rfxtrx_core.RFX_DEVICES) diff --git a/tests/components/sensor/test_ring.py b/tests/components/sensor/test_ring.py index 05685376e..384407917 100644 --- a/tests/components/sensor/test_ring.py +++ b/tests/components/sensor/test_ring.py @@ -72,40 +72,40 @@ class TestRingSensorSetup(unittest.TestCase): for device in self.DEVICES: device.update() if device.name == 'Front Battery': - self.assertEqual(80, device.state) - self.assertEqual('hp_cam_v1', - device.device_state_attributes['kind']) - self.assertEqual('stickup_cams', - device.device_state_attributes['type']) + assert 80 == device.state + assert 'hp_cam_v1' == \ + device.device_state_attributes['kind'] + assert 'stickup_cams' == \ + device.device_state_attributes['type'] if device.name == 'Front Door Battery': - self.assertEqual(100, device.state) - self.assertEqual('lpd_v1', - device.device_state_attributes['kind']) - self.assertNotEqual('chimes', - device.device_state_attributes['type']) + assert 100 == device.state + assert 'lpd_v1' == \ + device.device_state_attributes['kind'] + assert 'chimes' != \ + device.device_state_attributes['type'] if device.name == 'Downstairs Volume': - self.assertEqual(2, device.state) - self.assertEqual('1.2.3', - device.device_state_attributes['firmware']) - self.assertEqual('ring_mock_wifi', - device.device_state_attributes['wifi_name']) - self.assertEqual('mdi:bell-ring', device.icon) - self.assertEqual('chimes', - device.device_state_attributes['type']) + assert 2 == device.state + assert '1.2.3' == \ + device.device_state_attributes['firmware'] + assert 'ring_mock_wifi' == \ + device.device_state_attributes['wifi_name'] + assert 'mdi:bell-ring' == device.icon + assert 'chimes' == \ + device.device_state_attributes['type'] if device.name == 'Front Door Last Activity': - self.assertFalse(device.device_state_attributes['answered']) - self.assertEqual('America/New_York', - device.device_state_attributes['timezone']) + assert not device.device_state_attributes['answered'] + assert 'America/New_York' == \ + device.device_state_attributes['timezone'] if device.name == 'Downstairs WiFi Signal Strength': - self.assertEqual(-39, device.state) + assert -39 == device.state if device.name == 'Front Door WiFi Signal Category': - self.assertEqual('good', device.state) + assert 'good' == device.state if device.name == 'Front Door WiFi Signal Strength': - self.assertEqual(-58, device.state) + assert -58 == device.state - self.assertIsNone(device.entity_picture) - self.assertEqual(ATTRIBUTION, - device.device_state_attributes['attribution']) + assert device.entity_picture is None + assert ATTRIBUTION == \ + device.device_state_attributes['attribution'] diff --git a/tests/components/sensor/test_season.py b/tests/components/sensor/test_season.py index 21e18a00c..20432857a 100644 --- a/tests/components/sensor/test_season.py +++ b/tests/components/sensor/test_season.py @@ -79,8 +79,8 @@ class TestSeason(unittest.TestCase): summer_day = datetime(2017, 9, 3, 0, 0) current_season = season.get_season(summer_day, season.NORTHERN, season.TYPE_ASTRONOMICAL) - self.assertEqual(season.STATE_SUMMER, - current_season) + assert season.STATE_SUMMER == \ + current_season def test_season_should_be_summer_northern_meteorological(self): """Test that season should be summer.""" @@ -88,8 +88,8 @@ class TestSeason(unittest.TestCase): summer_day = datetime(2017, 8, 13, 0, 0) current_season = season.get_season(summer_day, season.NORTHERN, season.TYPE_METEOROLOGICAL) - self.assertEqual(season.STATE_SUMMER, - current_season) + assert season.STATE_SUMMER == \ + current_season def test_season_should_be_autumn_northern_astronomical(self): """Test that season should be autumn.""" @@ -97,8 +97,8 @@ class TestSeason(unittest.TestCase): autumn_day = datetime(2017, 9, 23, 0, 0) current_season = season.get_season(autumn_day, season.NORTHERN, season.TYPE_ASTRONOMICAL) - self.assertEqual(season.STATE_AUTUMN, - current_season) + assert season.STATE_AUTUMN == \ + current_season def test_season_should_be_autumn_northern_meteorological(self): """Test that season should be autumn.""" @@ -106,8 +106,8 @@ class TestSeason(unittest.TestCase): autumn_day = datetime(2017, 9, 3, 0, 0) current_season = season.get_season(autumn_day, season.NORTHERN, season.TYPE_METEOROLOGICAL) - self.assertEqual(season.STATE_AUTUMN, - current_season) + assert season.STATE_AUTUMN == \ + current_season def test_season_should_be_winter_northern_astronomical(self): """Test that season should be winter.""" @@ -115,8 +115,8 @@ class TestSeason(unittest.TestCase): winter_day = datetime(2017, 12, 25, 0, 0) current_season = season.get_season(winter_day, season.NORTHERN, season.TYPE_ASTRONOMICAL) - self.assertEqual(season.STATE_WINTER, - current_season) + assert season.STATE_WINTER == \ + current_season def test_season_should_be_winter_northern_meteorological(self): """Test that season should be winter.""" @@ -124,8 +124,8 @@ class TestSeason(unittest.TestCase): winter_day = datetime(2017, 12, 3, 0, 0) current_season = season.get_season(winter_day, season.NORTHERN, season.TYPE_METEOROLOGICAL) - self.assertEqual(season.STATE_WINTER, - current_season) + assert season.STATE_WINTER == \ + current_season def test_season_should_be_spring_northern_astronomical(self): """Test that season should be spring.""" @@ -133,8 +133,8 @@ class TestSeason(unittest.TestCase): spring_day = datetime(2017, 4, 1, 0, 0) current_season = season.get_season(spring_day, season.NORTHERN, season.TYPE_ASTRONOMICAL) - self.assertEqual(season.STATE_SPRING, - current_season) + assert season.STATE_SPRING == \ + current_season def test_season_should_be_spring_northern_meteorological(self): """Test that season should be spring.""" @@ -142,8 +142,8 @@ class TestSeason(unittest.TestCase): spring_day = datetime(2017, 3, 3, 0, 0) current_season = season.get_season(spring_day, season.NORTHERN, season.TYPE_METEOROLOGICAL) - self.assertEqual(season.STATE_SPRING, - current_season) + assert season.STATE_SPRING == \ + current_season def test_season_should_be_winter_southern_astronomical(self): """Test that season should be winter.""" @@ -151,8 +151,8 @@ class TestSeason(unittest.TestCase): winter_day = datetime(2017, 9, 3, 0, 0) current_season = season.get_season(winter_day, season.SOUTHERN, season.TYPE_ASTRONOMICAL) - self.assertEqual(season.STATE_WINTER, - current_season) + assert season.STATE_WINTER == \ + current_season def test_season_should_be_winter_southern_meteorological(self): """Test that season should be winter.""" @@ -160,8 +160,8 @@ class TestSeason(unittest.TestCase): winter_day = datetime(2017, 8, 13, 0, 0) current_season = season.get_season(winter_day, season.SOUTHERN, season.TYPE_METEOROLOGICAL) - self.assertEqual(season.STATE_WINTER, - current_season) + assert season.STATE_WINTER == \ + current_season def test_season_should_be_spring_southern_astronomical(self): """Test that season should be spring.""" @@ -169,8 +169,8 @@ class TestSeason(unittest.TestCase): spring_day = datetime(2017, 9, 23, 0, 0) current_season = season.get_season(spring_day, season.SOUTHERN, season.TYPE_ASTRONOMICAL) - self.assertEqual(season.STATE_SPRING, - current_season) + assert season.STATE_SPRING == \ + current_season def test_season_should_be_spring_southern_meteorological(self): """Test that season should be spring.""" @@ -178,8 +178,8 @@ class TestSeason(unittest.TestCase): spring_day = datetime(2017, 9, 3, 0, 0) current_season = season.get_season(spring_day, season.SOUTHERN, season.TYPE_METEOROLOGICAL) - self.assertEqual(season.STATE_SPRING, - current_season) + assert season.STATE_SPRING == \ + current_season def test_season_should_be_summer_southern_astronomical(self): """Test that season should be summer.""" @@ -187,8 +187,8 @@ class TestSeason(unittest.TestCase): summer_day = datetime(2017, 12, 25, 0, 0) current_season = season.get_season(summer_day, season.SOUTHERN, season.TYPE_ASTRONOMICAL) - self.assertEqual(season.STATE_SUMMER, - current_season) + assert season.STATE_SUMMER == \ + current_season def test_season_should_be_summer_southern_meteorological(self): """Test that season should be summer.""" @@ -196,8 +196,8 @@ class TestSeason(unittest.TestCase): summer_day = datetime(2017, 12, 3, 0, 0) current_season = season.get_season(summer_day, season.SOUTHERN, season.TYPE_METEOROLOGICAL) - self.assertEqual(season.STATE_SUMMER, - current_season) + assert season.STATE_SUMMER == \ + current_season def test_season_should_be_autumn_southern_astronomical(self): """Test that season should be spring.""" @@ -205,8 +205,8 @@ class TestSeason(unittest.TestCase): autumn_day = datetime(2017, 4, 1, 0, 0) current_season = season.get_season(autumn_day, season.SOUTHERN, season.TYPE_ASTRONOMICAL) - self.assertEqual(season.STATE_AUTUMN, - current_season) + assert season.STATE_AUTUMN == \ + current_season def test_season_should_be_autumn_southern_meteorological(self): """Test that season should be autumn.""" @@ -214,8 +214,8 @@ class TestSeason(unittest.TestCase): autumn_day = datetime(2017, 3, 3, 0, 0) current_season = season.get_season(autumn_day, season.SOUTHERN, season.TYPE_METEOROLOGICAL) - self.assertEqual(season.STATE_AUTUMN, - current_season) + assert season.STATE_AUTUMN == \ + current_season def test_on_equator_results_in_none(self): """Test that season should be unknown.""" @@ -224,40 +224,40 @@ class TestSeason(unittest.TestCase): current_season = season.get_season(summer_day, season.EQUATOR, season.TYPE_ASTRONOMICAL) - self.assertEqual(None, current_season) + assert current_season is None def test_setup_hemisphere_northern(self): """Test platform setup of northern hemisphere.""" self.hass.config.latitude = HEMISPHERE_NORTHERN[ 'homeassistant']['latitude'] assert setup_component(self.hass, 'sensor', HEMISPHERE_NORTHERN) - self.assertEqual(self.hass.config.as_dict()['latitude'], - HEMISPHERE_NORTHERN['homeassistant']['latitude']) + assert self.hass.config.as_dict()['latitude'] == \ + HEMISPHERE_NORTHERN['homeassistant']['latitude'] state = self.hass.states.get('sensor.season') - self.assertEqual(state.attributes.get('friendly_name'), 'Season') + assert state.attributes.get('friendly_name') == 'Season' def test_setup_hemisphere_southern(self): """Test platform setup of southern hemisphere.""" self.hass.config.latitude = HEMISPHERE_SOUTHERN[ 'homeassistant']['latitude'] assert setup_component(self.hass, 'sensor', HEMISPHERE_SOUTHERN) - self.assertEqual(self.hass.config.as_dict()['latitude'], - HEMISPHERE_SOUTHERN['homeassistant']['latitude']) + assert self.hass.config.as_dict()['latitude'] == \ + HEMISPHERE_SOUTHERN['homeassistant']['latitude'] state = self.hass.states.get('sensor.season') - self.assertEqual(state.attributes.get('friendly_name'), 'Season') + assert state.attributes.get('friendly_name') == 'Season' def test_setup_hemisphere_equator(self): """Test platform setup of equator.""" self.hass.config.latitude = HEMISPHERE_EQUATOR[ 'homeassistant']['latitude'] assert setup_component(self.hass, 'sensor', HEMISPHERE_EQUATOR) - self.assertEqual(self.hass.config.as_dict()['latitude'], - HEMISPHERE_EQUATOR['homeassistant']['latitude']) + assert self.hass.config.as_dict()['latitude'] == \ + HEMISPHERE_EQUATOR['homeassistant']['latitude'] state = self.hass.states.get('sensor.season') - self.assertEqual(state.attributes.get('friendly_name'), 'Season') + assert state.attributes.get('friendly_name') == 'Season' def test_setup_hemisphere_empty(self): """Test platform setup of missing latlong.""" self.hass.config.latitude = None assert setup_component(self.hass, 'sensor', HEMISPHERE_EMPTY) - self.assertEqual(self.hass.config.as_dict()['latitude'], None) + assert self.hass.config.as_dict()['latitude']is None diff --git a/tests/components/sensor/test_sigfox.py b/tests/components/sensor/test_sigfox.py index 569fab584..c785d272f 100644 --- a/tests/components/sensor/test_sigfox.py +++ b/tests/components/sensor/test_sigfox.py @@ -42,8 +42,7 @@ class TestSigfoxSensor(unittest.TestCase): with requests_mock.Mocker() as mock_req: url = re.compile(API_URL + 'devicetypes') mock_req.get(url, text='{}', status_code=401) - self.assertTrue( - setup_component(self.hass, 'sensor', VALID_CONFIG)) + assert setup_component(self.hass, 'sensor', VALID_CONFIG) assert len(self.hass.states.entity_ids()) == 0 def test_valid_credentials(self): @@ -59,8 +58,7 @@ class TestSigfoxSensor(unittest.TestCase): url3 = re.compile(API_URL + 'devices/fake_id/messages*') mock_req.get(url3, text=VALID_MESSAGE) - self.assertTrue( - setup_component(self.hass, 'sensor', VALID_CONFIG)) + assert setup_component(self.hass, 'sensor', VALID_CONFIG) assert len(self.hass.states.entity_ids()) == 1 state = self.hass.states.get('sensor.sigfox_fake_id') diff --git a/tests/components/sensor/test_simulated.py b/tests/components/sensor/test_simulated.py index 50552baa3..c51e281d1 100644 --- a/tests/components/sensor/test_simulated.py +++ b/tests/components/sensor/test_simulated.py @@ -28,7 +28,7 @@ class TestSimulatedSensor(unittest.TestCase): 'sensor': { 'platform': 'simulated'} } - self.assertTrue(setup_component(self.hass, 'sensor', config)) + assert setup_component(self.hass, 'sensor', config) self.hass.block_till_done() assert len(self.hass.states.entity_ids()) == 1 diff --git a/tests/components/sensor/test_sleepiq.py b/tests/components/sensor/test_sleepiq.py index 646f8e5d8..96787473a 100644 --- a/tests/components/sensor/test_sleepiq.py +++ b/tests/components/sensor/test_sleepiq.py @@ -51,12 +51,12 @@ class TestSleepIQSensorSetup(unittest.TestCase): self.config, self.add_entities, MagicMock()) - self.assertEqual(2, len(self.DEVICES)) + assert 2 == len(self.DEVICES) left_side = self.DEVICES[1] - self.assertEqual('SleepNumber ILE Test1 SleepNumber', left_side.name) - self.assertEqual(40, left_side.state) + assert 'SleepNumber ILE Test1 SleepNumber' == left_side.name + assert 40 == left_side.state right_side = self.DEVICES[0] - self.assertEqual('SleepNumber ILE Test2 SleepNumber', right_side.name) - self.assertEqual(80, right_side.state) + assert 'SleepNumber ILE Test2 SleepNumber' == right_side.name + assert 80 == right_side.state diff --git a/tests/components/sensor/test_sonarr.py b/tests/components/sensor/test_sonarr.py index e44d3d9a9..e8c7c17d0 100644 --- a/tests/components/sensor/test_sonarr.py +++ b/tests/components/sensor/test_sonarr.py @@ -610,14 +610,12 @@ class TestSonarrSetup(unittest.TestCase): sonarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual('263.10', device.state) - self.assertEqual('mdi:harddisk', device.icon) - self.assertEqual('GB', device.unit_of_measurement) - self.assertEqual('Sonarr Disk Space', device.name) - self.assertEqual( - '263.10/465.42GB (56.53%)', + assert '263.10' == device.state + assert 'mdi:harddisk' == device.icon + assert 'GB' == device.unit_of_measurement + assert 'Sonarr Disk Space' == device.name + assert '263.10/465.42GB (56.53%)' == \ device.device_state_attributes["/data"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_diskspace_paths(self, req_mock): @@ -637,14 +635,12 @@ class TestSonarrSetup(unittest.TestCase): sonarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual('263.10', device.state) - self.assertEqual('mdi:harddisk', device.icon) - self.assertEqual('GB', device.unit_of_measurement) - self.assertEqual('Sonarr Disk Space', device.name) - self.assertEqual( - '263.10/465.42GB (56.53%)', + assert '263.10' == device.state + assert 'mdi:harddisk' == device.icon + assert 'GB' == device.unit_of_measurement + assert 'Sonarr Disk Space' == device.name + assert '263.10/465.42GB (56.53%)' == \ device.device_state_attributes["/data"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_commands(self, req_mock): @@ -664,14 +660,12 @@ class TestSonarrSetup(unittest.TestCase): sonarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('mdi:code-braces', device.icon) - self.assertEqual('Commands', device.unit_of_measurement) - self.assertEqual('Sonarr Commands', device.name) - self.assertEqual( - 'pending', + assert 1 == device.state + assert 'mdi:code-braces' == device.icon + assert 'Commands' == device.unit_of_measurement + assert 'Sonarr Commands' == device.name + assert 'pending' == \ device.device_state_attributes["RescanSeries"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_queue(self, req_mock): @@ -691,14 +685,12 @@ class TestSonarrSetup(unittest.TestCase): sonarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('mdi:download', device.icon) - self.assertEqual('Episodes', device.unit_of_measurement) - self.assertEqual('Sonarr Queue', device.name) - self.assertEqual( - '100.00%', + assert 1 == device.state + assert 'mdi:download' == device.icon + assert 'Episodes' == device.unit_of_measurement + assert 'Sonarr Queue' == device.name + assert '100.00%' == \ device.device_state_attributes["Game of Thrones S03E08"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_series(self, req_mock): @@ -718,14 +710,12 @@ class TestSonarrSetup(unittest.TestCase): sonarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('mdi:television', device.icon) - self.assertEqual('Shows', device.unit_of_measurement) - self.assertEqual('Sonarr Series', device.name) - self.assertEqual( - '26/26 Episodes', + assert 1 == device.state + assert 'mdi:television' == device.icon + assert 'Shows' == device.unit_of_measurement + assert 'Sonarr Series' == device.name + assert '26/26 Episodes' == \ device.device_state_attributes["Marvel's Daredevil"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_wanted(self, req_mock): @@ -745,14 +735,12 @@ class TestSonarrSetup(unittest.TestCase): sonarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('mdi:television', device.icon) - self.assertEqual('Episodes', device.unit_of_measurement) - self.assertEqual('Sonarr Wanted', device.name) - self.assertEqual( - '2014-02-03', + assert 1 == device.state + assert 'mdi:television' == device.icon + assert 'Episodes' == device.unit_of_measurement + assert 'Sonarr Wanted' == device.name + assert '2014-02-03' == \ device.device_state_attributes["Archer (2009) S05E04"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_upcoming_multiple_days(self, req_mock): @@ -772,14 +760,12 @@ class TestSonarrSetup(unittest.TestCase): sonarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('mdi:television', device.icon) - self.assertEqual('Episodes', device.unit_of_measurement) - self.assertEqual('Sonarr Upcoming', device.name) - self.assertEqual( - 'S04E11', + assert 1 == device.state + assert 'mdi:television' == device.icon + assert 'Episodes' == device.unit_of_measurement + assert 'Sonarr Upcoming' == device.name + assert 'S04E11' == \ device.device_state_attributes["Bob's Burgers"] - ) @pytest.mark.skip @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) @@ -803,14 +789,12 @@ class TestSonarrSetup(unittest.TestCase): sonarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('mdi:television', device.icon) - self.assertEqual('Episodes', device.unit_of_measurement) - self.assertEqual('Sonarr Upcoming', device.name) - self.assertEqual( - 'S04E11', + assert 1 == device.state + assert 'mdi:television' == device.icon + assert 'Episodes' == device.unit_of_measurement + assert 'Sonarr Upcoming' == device.name + assert 'S04E11' == \ device.device_state_attributes["Bob's Burgers"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_system_status(self, req_mock): @@ -830,12 +814,11 @@ class TestSonarrSetup(unittest.TestCase): sonarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual('2.0.0.1121', device.state) - self.assertEqual('mdi:information', device.icon) - self.assertEqual('Sonarr Status', device.name) - self.assertEqual( - '6.2.9200.0', - device.device_state_attributes['osVersion']) + assert '2.0.0.1121' == device.state + assert 'mdi:information' == device.icon + assert 'Sonarr Status' == device.name + assert '6.2.9200.0' == \ + device.device_state_attributes['osVersion'] @pytest.mark.skip @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) @@ -857,15 +840,13 @@ class TestSonarrSetup(unittest.TestCase): sonarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(1, device.state) - self.assertEqual('s', device.ssl) - self.assertEqual('mdi:television', device.icon) - self.assertEqual('Episodes', device.unit_of_measurement) - self.assertEqual('Sonarr Upcoming', device.name) - self.assertEqual( - 'S04E11', + assert 1 == device.state + assert 's' == device.ssl + assert 'mdi:television' == device.icon + assert 'Episodes' == device.unit_of_measurement + assert 'Sonarr Upcoming' == device.name + assert 'S04E11' == \ device.device_state_attributes["Bob's Burgers"] - ) @unittest.mock.patch('requests.get', side_effect=mocked_exception) def test_exception_handling(self, req_mock): @@ -885,4 +866,4 @@ class TestSonarrSetup(unittest.TestCase): sonarr.setup_platform(self.hass, config, self.add_entities, None) for device in self.DEVICES: device.update() - self.assertEqual(None, device.state) + assert device.state is None diff --git a/tests/components/sensor/test_sql.py b/tests/components/sensor/test_sql.py index 7665b5c90..c966af653 100644 --- a/tests/components/sensor/test_sql.py +++ b/tests/components/sensor/test_sql.py @@ -61,4 +61,4 @@ class TestSQLSensor(unittest.TestCase): assert setup_component(self.hass, 'sensor', config) state = self.hass.states.get('sensor.count_tables') - self.assertEqual(state.state, STATE_UNKNOWN) + assert state.state == STATE_UNKNOWN diff --git a/tests/components/sensor/test_statistics.py b/tests/components/sensor/test_statistics.py index e7cfec4d8..0bf9ecd8c 100644 --- a/tests/components/sensor/test_statistics.py +++ b/tests/components/sensor/test_statistics.py @@ -54,7 +54,7 @@ class TestStatisticsSensor(unittest.TestCase): state = self.hass.states.get('sensor.test_count') - self.assertEqual(str(len(values)), state.state) + assert str(len(values)) == state.state def test_sensor_source(self): """Test if source is a sensor.""" @@ -73,20 +73,20 @@ class TestStatisticsSensor(unittest.TestCase): state = self.hass.states.get('sensor.test_mean') - self.assertEqual(str(self.mean), state.state) - self.assertEqual(self.min, state.attributes.get('min_value')) - self.assertEqual(self.max, state.attributes.get('max_value')) - self.assertEqual(self.variance, state.attributes.get('variance')) - self.assertEqual(self.median, state.attributes.get('median')) - self.assertEqual(self.deviation, - state.attributes.get('standard_deviation')) - self.assertEqual(self.mean, state.attributes.get('mean')) - self.assertEqual(self.count, state.attributes.get('count')) - self.assertEqual(self.total, state.attributes.get('total')) - self.assertEqual('°C', state.attributes.get('unit_of_measurement')) - self.assertEqual(self.change, state.attributes.get('change')) - self.assertEqual(self.average_change, - state.attributes.get('average_change')) + assert str(self.mean) == state.state + assert self.min == state.attributes.get('min_value') + assert self.max == state.attributes.get('max_value') + assert self.variance == state.attributes.get('variance') + assert self.median == state.attributes.get('median') + assert self.deviation == \ + state.attributes.get('standard_deviation') + assert self.mean == state.attributes.get('mean') + assert self.count == state.attributes.get('count') + assert self.total == state.attributes.get('total') + assert '°C' == state.attributes.get('unit_of_measurement') + assert self.change == state.attributes.get('change') + assert self.average_change == \ + state.attributes.get('average_change') def test_sampling_size(self): """Test rotation.""" @@ -106,8 +106,8 @@ class TestStatisticsSensor(unittest.TestCase): state = self.hass.states.get('sensor.test_mean') - self.assertEqual(3.8, state.attributes.get('min_value')) - self.assertEqual(14, state.attributes.get('max_value')) + assert 3.8 == state.attributes.get('min_value') + assert 14 == state.attributes.get('max_value') def test_sampling_size_1(self): """Test validity of stats requiring only one sample.""" @@ -128,18 +128,18 @@ class TestStatisticsSensor(unittest.TestCase): state = self.hass.states.get('sensor.test_mean') # require only one data point - self.assertEqual(self.values[-1], state.attributes.get('min_value')) - self.assertEqual(self.values[-1], state.attributes.get('max_value')) - self.assertEqual(self.values[-1], state.attributes.get('mean')) - self.assertEqual(self.values[-1], state.attributes.get('median')) - self.assertEqual(self.values[-1], state.attributes.get('total')) - self.assertEqual(0, state.attributes.get('change')) - self.assertEqual(0, state.attributes.get('average_change')) + assert self.values[-1] == state.attributes.get('min_value') + assert self.values[-1] == state.attributes.get('max_value') + assert self.values[-1] == state.attributes.get('mean') + assert self.values[-1] == state.attributes.get('median') + assert self.values[-1] == state.attributes.get('total') + assert 0 == state.attributes.get('change') + assert 0 == state.attributes.get('average_change') # require at least two data points - self.assertEqual(STATE_UNKNOWN, state.attributes.get('variance')) - self.assertEqual(STATE_UNKNOWN, - state.attributes.get('standard_deviation')) + assert STATE_UNKNOWN == state.attributes.get('variance') + assert STATE_UNKNOWN == \ + state.attributes.get('standard_deviation') def test_max_age(self): """Test value deprecation.""" @@ -170,8 +170,8 @@ class TestStatisticsSensor(unittest.TestCase): state = self.hass.states.get('sensor.test_mean') - self.assertEqual(6, state.attributes.get('min_value')) - self.assertEqual(14, state.attributes.get('max_value')) + assert 6 == state.attributes.get('min_value') + assert 14 == state.attributes.get('max_value') def test_change_rate(self): """Test min_age/max_age and change_rate.""" @@ -202,12 +202,12 @@ class TestStatisticsSensor(unittest.TestCase): state = self.hass.states.get('sensor.test_mean') - self.assertEqual(datetime(2017, 8, 2, 12, 23, 42, tzinfo=dt_util.UTC), - state.attributes.get('min_age')) - self.assertEqual(datetime(2017, 8, 2, 12, 23 + self.count - 1, 42, - tzinfo=dt_util.UTC), - state.attributes.get('max_age')) - self.assertEqual(self.change_rate, state.attributes.get('change_rate')) + assert datetime(2017, 8, 2, 12, 23, 42, tzinfo=dt_util.UTC) == \ + state.attributes.get('min_age') + assert datetime(2017, 8, 2, 12, 23 + self.count - 1, 42, + tzinfo=dt_util.UTC) == \ + state.attributes.get('max_age') + assert self.change_rate == state.attributes.get('change_rate') def test_initialize_from_database(self): """Test initializing the statistics from the database.""" @@ -232,4 +232,4 @@ class TestStatisticsSensor(unittest.TestCase): }) # check if the result is as in test_sensor_source() state = self.hass.states.get('sensor.test_mean') - self.assertEqual(str(self.mean), state.state) + assert str(self.mean) == state.state diff --git a/tests/components/sensor/test_transport_nsw.py b/tests/components/sensor/test_transport_nsw.py index fe9332729..c0ad4be41 100644 --- a/tests/components/sensor/test_transport_nsw.py +++ b/tests/components/sensor/test_transport_nsw.py @@ -43,8 +43,8 @@ class TestRMVtransportSensor(unittest.TestCase): """Test minimal TransportNSW configuration.""" assert setup_component(self.hass, 'sensor', VALID_CONFIG) state = self.hass.states.get('sensor.next_bus') - self.assertEqual(state.state, '16') - self.assertEqual(state.attributes['stop_id'], '209516') - self.assertEqual(state.attributes['route'], '199') - self.assertEqual(state.attributes['delay'], 6) - self.assertEqual(state.attributes['real_time'], 'y') + assert state.state == '16' + assert state.attributes['stop_id'] == '209516' + assert state.attributes['route'] == '199' + assert state.attributes['delay'] == 6 + assert state.attributes['real_time'] == 'y' diff --git a/tests/components/sensor/test_uk_transport.py b/tests/components/sensor/test_uk_transport.py index b051d8e1a..65e6b7f0f 100644 --- a/tests/components/sensor/test_uk_transport.py +++ b/tests/components/sensor/test_uk_transport.py @@ -50,8 +50,8 @@ class TestUkTransportSensor(unittest.TestCase): with requests_mock.Mocker() as mock_req: uri = re.compile(UkTransportSensor.TRANSPORT_API_URL_BASE + '*') mock_req.get(uri, text=load_fixture('uk_transport_bus.json')) - self.assertTrue( - setup_component(self.hass, 'sensor', {'sensor': self.config})) + assert setup_component( + self.hass, 'sensor', {'sensor': self.config}) bus_state = self.hass.states.get('sensor.next_bus_to_wantage') @@ -73,8 +73,8 @@ class TestUkTransportSensor(unittest.TestCase): with requests_mock.Mocker() as mock_req: uri = re.compile(UkTransportSensor.TRANSPORT_API_URL_BASE + '*') mock_req.get(uri, text=load_fixture('uk_transport_train.json')) - self.assertTrue( - setup_component(self.hass, 'sensor', {'sensor': self.config})) + assert setup_component( + self.hass, 'sensor', {'sensor': self.config}) train_state = self.hass.states.get('sensor.next_train_to_WAT') diff --git a/tests/components/sensor/test_uptime.py b/tests/components/sensor/test_uptime.py index a919e7d20..00552dd9e 100644 --- a/tests/components/sensor/test_uptime.py +++ b/tests/components/sensor/test_uptime.py @@ -62,56 +62,56 @@ class TestUptimeSensor(unittest.TestCase): def test_uptime_sensor_days_output(self): """Test uptime sensor output data.""" sensor = UptimeSensor('test', 'days') - self.assertEqual(sensor.unit_of_measurement, 'days') + assert sensor.unit_of_measurement == 'days' new_time = sensor.initial + timedelta(days=1) with patch('homeassistant.util.dt.now', return_value=new_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop ).result() - self.assertEqual(sensor.state, 1.00) + assert sensor.state == 1.00 new_time = sensor.initial + timedelta(days=111.499) with patch('homeassistant.util.dt.now', return_value=new_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop ).result() - self.assertEqual(sensor.state, 111.50) + assert sensor.state == 111.50 def test_uptime_sensor_hours_output(self): """Test uptime sensor output data.""" sensor = UptimeSensor('test', 'hours') - self.assertEqual(sensor.unit_of_measurement, 'hours') + assert sensor.unit_of_measurement == 'hours' new_time = sensor.initial + timedelta(hours=16) with patch('homeassistant.util.dt.now', return_value=new_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop ).result() - self.assertEqual(sensor.state, 16.00) + assert sensor.state == 16.00 new_time = sensor.initial + timedelta(hours=72.499) with patch('homeassistant.util.dt.now', return_value=new_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop ).result() - self.assertEqual(sensor.state, 72.50) + assert sensor.state == 72.50 def test_uptime_sensor_minutes_output(self): """Test uptime sensor output data.""" sensor = UptimeSensor('test', 'minutes') - self.assertEqual(sensor.unit_of_measurement, 'minutes') + assert sensor.unit_of_measurement == 'minutes' new_time = sensor.initial + timedelta(minutes=16) with patch('homeassistant.util.dt.now', return_value=new_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop ).result() - self.assertEqual(sensor.state, 16.00) + assert sensor.state == 16.00 new_time = sensor.initial + timedelta(minutes=12.499) with patch('homeassistant.util.dt.now', return_value=new_time): run_coroutine_threadsafe( sensor.async_update(), self.hass.loop ).result() - self.assertEqual(sensor.state, 12.50) + assert sensor.state == 12.50 diff --git a/tests/components/sensor/test_version.py b/tests/components/sensor/test_version.py index 270cfd170..e4ddbd153 100644 --- a/tests/components/sensor/test_version.py +++ b/tests/components/sensor/test_version.py @@ -47,4 +47,4 @@ class TestVersionSensor(unittest.TestCase): state = self.hass.states.get('sensor.test') - self.assertEqual(state.state, '10.0') + assert state.state == '10.0' diff --git a/tests/components/sensor/test_vultr.py b/tests/components/sensor/test_vultr.py index ee2dd35dc..294657c22 100644 --- a/tests/components/sensor/test_vultr.py +++ b/tests/components/sensor/test_vultr.py @@ -73,9 +73,9 @@ class TestVultrSensorSetup(unittest.TestCase): setup = vultr.setup_platform( self.hass, config, self.add_entities, None) - self.assertIsNone(setup) + assert setup is None - self.assertEqual(5, len(self.DEVICES)) + assert 5 == len(self.DEVICES) tested = 0 @@ -83,47 +83,46 @@ class TestVultrSensorSetup(unittest.TestCase): # Test pre update if device.subscription == '576965': - self.assertEqual(vultr.DEFAULT_NAME, device.name) + assert vultr.DEFAULT_NAME == device.name device.update() if device.unit_of_measurement == 'GB': # Test Bandwidth Used if device.subscription == '576965': - self.assertEqual( - 'Vultr my new server Current Bandwidth Used', - device.name) - self.assertEqual('mdi:chart-histogram', device.icon) - self.assertEqual(131.51, device.state) - self.assertEqual('mdi:chart-histogram', device.icon) + assert 'Vultr my new server Current Bandwidth Used' == \ + device.name + assert 'mdi:chart-histogram' == device.icon + assert 131.51 == device.state + assert 'mdi:chart-histogram' == device.icon tested += 1 elif device.subscription == '123456': - self.assertEqual('Server Current Bandwidth Used', - device.name) - self.assertEqual(957.46, device.state) + assert 'Server Current Bandwidth Used' == \ + device.name + assert 957.46 == device.state tested += 1 elif device.unit_of_measurement == 'US$': # Test Pending Charges if device.subscription == '576965': # Default 'Vultr {} {}' - self.assertEqual('Vultr my new server Pending Charges', - device.name) - self.assertEqual('mdi:currency-usd', device.icon) - self.assertEqual(46.67, device.state) - self.assertEqual('mdi:currency-usd', device.icon) + assert 'Vultr my new server Pending Charges' == \ + device.name + assert 'mdi:currency-usd' == device.icon + assert 46.67 == device.state + assert 'mdi:currency-usd' == device.icon tested += 1 elif device.subscription == '123456': # Custom name with 1 {} - self.assertEqual('Server Pending Charges', device.name) - self.assertEqual('not a number', device.state) + assert 'Server Pending Charges' == device.name + assert 'not a number' == device.state tested += 1 elif device.subscription == '555555': # No {} in name - self.assertEqual('VPS Charges', device.name) - self.assertEqual(5.45, device.state) + assert 'VPS Charges' == device.name + assert 5.45 == device.state tested += 1 - self.assertEqual(tested, 5) + assert tested == 5 def test_invalid_sensor_config(self): """Test config type failures.""" @@ -162,5 +161,5 @@ class TestVultrSensorSetup(unittest.TestCase): no_sub_setup = vultr.setup_platform( self.hass, bad_conf, self.add_entities, None) - self.assertIsNone(no_sub_setup) - self.assertEqual(0, len(self.DEVICES)) + assert no_sub_setup is None + assert 0 == len(self.DEVICES) diff --git a/tests/components/sensor/test_worldclock.py b/tests/components/sensor/test_worldclock.py index 9c5392675..fc61d9210 100644 --- a/tests/components/sensor/test_worldclock.py +++ b/tests/components/sensor/test_worldclock.py @@ -21,7 +21,7 @@ class TestWorldClockSensor(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, 'sensor', config)) + assert setup_component(self.hass, 'sensor', config) def tearDown(self): """Stop everything that was started.""" diff --git a/tests/components/sensor/test_wsdot.py b/tests/components/sensor/test_wsdot.py index 8eb542b2b..b90529693 100644 --- a/tests/components/sensor/test_wsdot.py +++ b/tests/components/sensor/test_wsdot.py @@ -43,8 +43,7 @@ class TestWSDOT(unittest.TestCase): def test_setup_with_config(self): """Test the platform setup with configuration.""" - self.assertTrue( - setup_component(self.hass, 'sensor', {'wsdot': self.config})) + assert setup_component(self.hass, 'sensor', {'wsdot': self.config}) @requests_mock.Mocker() def test_setup(self, mock_req): @@ -52,12 +51,11 @@ class TestWSDOT(unittest.TestCase): uri = re.compile(RESOURCE + '*') mock_req.get(uri, text=load_fixture('wsdot.json')) wsdot.setup_platform(self.hass, self.config, self.add_entities) - self.assertEqual(len(self.entities), 1) + assert len(self.entities) == 1 sensor = self.entities[0] - self.assertEqual(sensor.name, 'I90 EB') - self.assertEqual(sensor.state, 11) - self.assertEqual(sensor.device_state_attributes[ATTR_DESCRIPTION], - 'Downtown Seattle to Downtown Bellevue via I-90') - self.assertEqual(sensor.device_state_attributes[ATTR_TIME_UPDATED], - datetime(2017, 1, 21, 15, 10, - tzinfo=timezone(timedelta(hours=-8)))) + assert sensor.name == 'I90 EB' + assert sensor.state == 11 + assert sensor.device_state_attributes[ATTR_DESCRIPTION] == \ + 'Downtown Seattle to Downtown Bellevue via I-90' + assert sensor.device_state_attributes[ATTR_TIME_UPDATED] == \ + datetime(2017, 1, 21, 15, 10, tzinfo=timezone(timedelta(hours=-8))) diff --git a/tests/components/sensor/test_yahoo_finance.py b/tests/components/sensor/test_yahoo_finance.py index 7b46ad99d..d442b9c9b 100644 --- a/tests/components/sensor/test_yahoo_finance.py +++ b/tests/components/sensor/test_yahoo_finance.py @@ -39,6 +39,6 @@ class TestYahooFinanceSetup(unittest.TestCase): 'sensor': VALID_CONFIG}) state = self.hass.states.get('sensor.yhoo') - self.assertEqual('41.69', state.attributes.get('open')) - self.assertEqual('41.79', state.attributes.get('prev_close')) - self.assertEqual('YHOO', state.attributes.get('unit_of_measurement')) + assert '41.69' == state.attributes.get('open') + assert '41.79' == state.attributes.get('prev_close') + assert 'YHOO' == state.attributes.get('unit_of_measurement') diff --git a/tests/components/sensor/test_yweather.py b/tests/components/sensor/test_yweather.py index 2912229d7..18bf8abeb 100644 --- a/tests/components/sensor/test_yweather.py +++ b/tests/components/sensor/test_yweather.py @@ -148,8 +148,8 @@ class TestWeather(unittest.TestCase): assert state is not None assert state.state == 'Mostly Cloudy' - self.assertEqual(state.attributes.get('friendly_name'), - 'Yweather Condition') + assert state.attributes.get('friendly_name') == \ + 'Yweather Condition' @MockDependency('yahooweather') @patch('yahooweather._yql_query', new=_yql_queryMock) @@ -161,59 +161,59 @@ class TestWeather(unittest.TestCase): state = self.hass.states.get('sensor.yweather_condition') assert state is not None - self.assertEqual(state.state, 'Mostly Cloudy') - self.assertEqual(state.attributes.get('condition_code'), - '28') - self.assertEqual(state.attributes.get('friendly_name'), - 'Yweather Condition') + assert state.state == 'Mostly Cloudy' + assert state.attributes.get('condition_code') == \ + '28' + assert state.attributes.get('friendly_name') == \ + 'Yweather Condition' state = self.hass.states.get('sensor.yweather_current') assert state is not None - self.assertEqual(state.state, 'Cloudy') - self.assertEqual(state.attributes.get('friendly_name'), - 'Yweather Current') + assert state.state == 'Cloudy' + assert state.attributes.get('friendly_name') == \ + 'Yweather Current' state = self.hass.states.get('sensor.yweather_temperature') assert state is not None - self.assertEqual(state.state, '18') - self.assertEqual(state.attributes.get('friendly_name'), - 'Yweather Temperature') + assert state.state == '18' + assert state.attributes.get('friendly_name') == \ + 'Yweather Temperature' state = self.hass.states.get('sensor.yweather_temperature_max') assert state is not None - self.assertEqual(state.state, '23') - self.assertEqual(state.attributes.get('friendly_name'), - 'Yweather Temperature max') + assert state.state == '23' + assert state.attributes.get('friendly_name') == \ + 'Yweather Temperature max' state = self.hass.states.get('sensor.yweather_temperature_min') assert state is not None - self.assertEqual(state.state, '16') - self.assertEqual(state.attributes.get('friendly_name'), - 'Yweather Temperature min') + assert state.state == '16' + assert state.attributes.get('friendly_name') == \ + 'Yweather Temperature min' state = self.hass.states.get('sensor.yweather_wind_speed') assert state is not None - self.assertEqual(state.state, '3.94') - self.assertEqual(state.attributes.get('friendly_name'), - 'Yweather Wind speed') + assert state.state == '3.94' + assert state.attributes.get('friendly_name') == \ + 'Yweather Wind speed' state = self.hass.states.get('sensor.yweather_pressure') assert state is not None - self.assertEqual(state.state, '1000.0') - self.assertEqual(state.attributes.get('friendly_name'), - 'Yweather Pressure') + assert state.state == '1000.0' + assert state.attributes.get('friendly_name') == \ + 'Yweather Pressure' state = self.hass.states.get('sensor.yweather_visibility') assert state is not None - self.assertEqual(state.state, '14.23') - self.assertEqual(state.attributes.get('friendly_name'), - 'Yweather Visibility') + assert state.state == '14.23' + assert state.attributes.get('friendly_name') == \ + 'Yweather Visibility' state = self.hass.states.get('sensor.yweather_humidity') assert state is not None - self.assertEqual(state.state, '71') - self.assertEqual(state.attributes.get('friendly_name'), - 'Yweather Humidity') + assert state.state == '71' + assert state.attributes.get('friendly_name') == \ + 'Yweather Humidity' @MockDependency('yahooweather') @patch('yahooweather._yql_query', new=_yql_queryMock) diff --git a/tests/components/switch/test_command_line.py b/tests/components/switch/test_command_line.py index a84281b43..06618e248 100644 --- a/tests/components/switch/test_command_line.py +++ b/tests/components/switch/test_command_line.py @@ -33,29 +33,29 @@ class TestCommandSwitch(unittest.TestCase): 'command_on': 'echo 1 > {}'.format(path), 'command_off': 'echo 0 > {}'.format(path), } - self.assertTrue(setup_component(self.hass, switch.DOMAIN, { + assert setup_component(self.hass, switch.DOMAIN, { 'switch': { 'platform': 'command_line', 'switches': { 'test': test_switch } } - })) + }) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state common.turn_on(self.hass, 'switch.test') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state common.turn_off(self.hass, 'switch.test') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state def test_state_value(self): """Test with state value.""" @@ -67,29 +67,29 @@ class TestCommandSwitch(unittest.TestCase): 'command_off': 'echo 0 > {}'.format(path), 'value_template': '{{ value=="1" }}' } - self.assertTrue(setup_component(self.hass, switch.DOMAIN, { + assert setup_component(self.hass, switch.DOMAIN, { 'switch': { 'platform': 'command_line', 'switches': { 'test': test_switch } } - })) + }) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state common.turn_on(self.hass, 'switch.test') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state common.turn_off(self.hass, 'switch.test') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state def test_state_json_value(self): """Test with state JSON value.""" @@ -103,29 +103,29 @@ class TestCommandSwitch(unittest.TestCase): 'command_off': 'echo \'{}\' > {}'.format(offcmd, path), 'value_template': '{{ value_json.status=="ok" }}' } - self.assertTrue(setup_component(self.hass, switch.DOMAIN, { + assert setup_component(self.hass, switch.DOMAIN, { 'switch': { 'platform': 'command_line', 'switches': { 'test': test_switch } } - })) + }) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state common.turn_on(self.hass, 'switch.test') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state common.turn_off(self.hass, 'switch.test') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state def test_state_code(self): """Test with state code.""" @@ -136,29 +136,29 @@ class TestCommandSwitch(unittest.TestCase): 'command_on': 'echo 1 > {}'.format(path), 'command_off': 'echo 0 > {}'.format(path), } - self.assertTrue(setup_component(self.hass, switch.DOMAIN, { + assert setup_component(self.hass, switch.DOMAIN, { 'switch': { 'platform': 'command_line', 'switches': { 'test': test_switch } } - })) + }) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state common.turn_on(self.hass, 'switch.test') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state common.turn_off(self.hass, 'switch.test') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state def test_assumed_state_should_be_true_if_command_state_is_none(self): """Test with state value.""" @@ -175,13 +175,13 @@ class TestCommandSwitch(unittest.TestCase): ] no_state_device = command_line.CommandSwitch(*init_args) - self.assertTrue(no_state_device.assumed_state) + assert no_state_device.assumed_state # Set state command init_args[-2] = 'cat {}' state_device = command_line.CommandSwitch(*init_args) - self.assertFalse(state_device.assumed_state) + assert not state_device.assumed_state def test_entity_id_set_correctly(self): """Test that entity_id is set correctly from object_id.""" @@ -196,5 +196,5 @@ class TestCommandSwitch(unittest.TestCase): ] test_switch = command_line.CommandSwitch(*init_args) - self.assertEqual(test_switch.entity_id, 'switch.test_device_name') - self.assertEqual(test_switch.name, 'Test friendly name!') + assert test_switch.entity_id == 'switch.test_device_name' + assert test_switch.name == 'Test friendly name!' diff --git a/tests/components/switch/test_flux.py b/tests/components/switch/test_flux.py index cb5207adb..dbe31e8f4 100644 --- a/tests/components/switch/test_flux.py +++ b/tests/components/switch/test_flux.py @@ -75,17 +75,16 @@ class TestSwitchFlux(unittest.TestCase): """Test the flux switch when it is off.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=10, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -110,23 +109,22 @@ class TestSwitchFlux(unittest.TestCase): self.hass, light.DOMAIN, SERVICE_TURN_ON) fire_time_changed(self.hass, test_time) self.hass.block_till_done() - self.assertEqual(0, len(turn_on_calls)) + assert 0 == len(turn_on_calls) def test_flux_before_sunrise(self): """Test the flux switch before sunrise.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=2, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -154,25 +152,24 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 112) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.606, 0.379]) + assert call.data[light.ATTR_BRIGHTNESS] == 112 + assert call.data[light.ATTR_XY_COLOR] == [0.606, 0.379] # pylint: disable=invalid-name def test_flux_after_sunrise_before_sunset(self): """Test the flux switch after sunrise and before sunset.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=8, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -201,25 +198,24 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 173) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.439, 0.37]) + assert call.data[light.ATTR_BRIGHTNESS] == 173 + assert call.data[light.ATTR_XY_COLOR] == [0.439, 0.37] # pylint: disable=invalid-name def test_flux_after_sunset_before_stop(self): """Test the flux switch after sunset and before stop.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=17, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -249,25 +245,24 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 146) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.506, 0.385]) + assert call.data[light.ATTR_BRIGHTNESS] == 146 + assert call.data[light.ATTR_XY_COLOR] == [0.506, 0.385] # pylint: disable=invalid-name def test_flux_after_stop_before_sunrise(self): """Test the flux switch after stop and before sunrise.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=23, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -295,25 +290,24 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 112) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.606, 0.379]) + assert call.data[light.ATTR_BRIGHTNESS] == 112 + assert call.data[light.ATTR_XY_COLOR] == [0.606, 0.379] # pylint: disable=invalid-name def test_flux_with_custom_start_stop_times(self): """Test the flux with custom start and stop times.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=17, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -344,8 +338,8 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 147) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.504, 0.385]) + assert call.data[light.ATTR_BRIGHTNESS] == 147 + assert call.data[light.ATTR_XY_COLOR] == [0.504, 0.385] def test_flux_before_sunrise_stop_next_day(self): """Test the flux switch before sunrise. @@ -354,17 +348,16 @@ class TestSwitchFlux(unittest.TestCase): """ platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=2, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -394,8 +387,8 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 112) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.606, 0.379]) + assert call.data[light.ATTR_BRIGHTNESS] == 112 + assert call.data[light.ATTR_XY_COLOR] == [0.606, 0.379] # pylint: disable=invalid-name def test_flux_after_sunrise_before_sunset_stop_next_day(self): @@ -406,17 +399,16 @@ class TestSwitchFlux(unittest.TestCase): """ platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=8, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -446,8 +438,8 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 173) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.439, 0.37]) + assert call.data[light.ATTR_BRIGHTNESS] == 173 + assert call.data[light.ATTR_XY_COLOR] == [0.439, 0.37] # pylint: disable=invalid-name def test_flux_after_sunset_before_midnight_stop_next_day(self): @@ -457,17 +449,16 @@ class TestSwitchFlux(unittest.TestCase): """ platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=23, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -496,8 +487,8 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 119) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.588, 0.386]) + assert call.data[light.ATTR_BRIGHTNESS] == 119 + assert call.data[light.ATTR_XY_COLOR] == [0.588, 0.386] # pylint: disable=invalid-name def test_flux_after_sunset_after_midnight_stop_next_day(self): @@ -507,17 +498,16 @@ class TestSwitchFlux(unittest.TestCase): """ platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=00, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -547,8 +537,8 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 114) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.601, 0.382]) + assert call.data[light.ATTR_BRIGHTNESS] == 114 + assert call.data[light.ATTR_XY_COLOR] == [0.601, 0.382] # pylint: disable=invalid-name def test_flux_after_stop_before_sunrise_stop_next_day(self): @@ -558,17 +548,16 @@ class TestSwitchFlux(unittest.TestCase): """ platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=2, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -598,25 +587,24 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 112) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.606, 0.379]) + assert call.data[light.ATTR_BRIGHTNESS] == 112 + assert call.data[light.ATTR_XY_COLOR] == [0.606, 0.379] # pylint: disable=invalid-name def test_flux_with_custom_colortemps(self): """Test the flux with custom start and stop colortemps.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=17, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -648,25 +636,24 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 159) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.469, 0.378]) + assert call.data[light.ATTR_BRIGHTNESS] == 159 + assert call.data[light.ATTR_XY_COLOR] == [0.469, 0.378] # pylint: disable=invalid-name def test_flux_with_custom_brightness(self): """Test the flux with custom start and stop colortemps.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=17, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -697,16 +684,15 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 255) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.506, 0.385]) + assert call.data[light.ATTR_BRIGHTNESS] == 255 + assert call.data[light.ATTR_XY_COLOR] == [0.506, 0.385] def test_flux_with_multiple_lights(self): """Test the flux switch with multiple light entities.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1, dev2, dev3 = platform.DEVICES common_light.turn_on(self.hass, entity_id=dev2.entity_id) @@ -715,19 +701,19 @@ class TestSwitchFlux(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None state = self.hass.states.get(dev2.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None state = self.hass.states.get(dev3.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('xy_color')) - self.assertIsNone(state.attributes.get('brightness')) + assert STATE_ON == state.state + assert state.attributes.get('xy_color') is None + assert state.attributes.get('brightness') is None test_time = dt_util.now().replace(hour=12, minute=0, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -760,29 +746,28 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 163) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.46, 0.376]) + assert call.data[light.ATTR_BRIGHTNESS] == 163 + assert call.data[light.ATTR_XY_COLOR] == [0.46, 0.376] call = turn_on_calls[-2] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 163) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.46, 0.376]) + assert call.data[light.ATTR_BRIGHTNESS] == 163 + assert call.data[light.ATTR_XY_COLOR] == [0.46, 0.376] call = turn_on_calls[-3] - self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 163) - self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.46, 0.376]) + assert call.data[light.ATTR_BRIGHTNESS] == 163 + assert call.data[light.ATTR_XY_COLOR] == [0.46, 0.376] def test_flux_with_mired(self): """Test the flux switch´s mode mired.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('color_temp')) + assert STATE_ON == state.state + assert state.attributes.get('color_temp') is None test_time = dt_util.now().replace(hour=8, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -812,22 +797,21 @@ class TestSwitchFlux(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] - self.assertEqual(call.data[light.ATTR_COLOR_TEMP], 269) + assert call.data[light.ATTR_COLOR_TEMP] == 269 def test_flux_with_rgb(self): """Test the flux switch´s mode rgb.""" platform = loader.get_component(self.hass, 'light.test') platform.init() - self.assertTrue( - setup_component(self.hass, light.DOMAIN, - {light.DOMAIN: {CONF_PLATFORM: 'test'}})) + assert setup_component(self.hass, light.DOMAIN, + {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) - self.assertEqual(STATE_ON, state.state) - self.assertIsNone(state.attributes.get('color_temp')) + assert STATE_ON == state.state + assert state.attributes.get('color_temp') is None test_time = dt_util.now().replace(hour=8, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) @@ -859,4 +843,4 @@ class TestSwitchFlux(unittest.TestCase): call = turn_on_calls[-1] rgb = (255, 198, 152) rounded_call = tuple(map(round, call.data[light.ATTR_RGB_COLOR])) - self.assertEqual(rounded_call, rgb) + assert rounded_call == rgb diff --git a/tests/components/switch/test_init.py b/tests/components/switch/test_init.py index a7462eecd..1a51457df 100644 --- a/tests/components/switch/test_init.py +++ b/tests/components/switch/test_init.py @@ -31,51 +31,48 @@ class TestSwitch(unittest.TestCase): def test_methods(self): """Test is_on, turn_on, turn_off methods.""" - self.assertTrue(setup_component( + assert setup_component( self.hass, switch.DOMAIN, {switch.DOMAIN: {CONF_PLATFORM: 'test'}} - )) - self.assertTrue(switch.is_on(self.hass)) - self.assertEqual( - STATE_ON, - self.hass.states.get(switch.ENTITY_ID_ALL_SWITCHES).state) - self.assertTrue(switch.is_on(self.hass, self.switch_1.entity_id)) - self.assertFalse(switch.is_on(self.hass, self.switch_2.entity_id)) - self.assertFalse(switch.is_on(self.hass, self.switch_3.entity_id)) + ) + assert switch.is_on(self.hass) + assert STATE_ON == \ + self.hass.states.get(switch.ENTITY_ID_ALL_SWITCHES).state + assert switch.is_on(self.hass, self.switch_1.entity_id) + assert not switch.is_on(self.hass, self.switch_2.entity_id) + assert not switch.is_on(self.hass, self.switch_3.entity_id) common.turn_off(self.hass, self.switch_1.entity_id) common.turn_on(self.hass, self.switch_2.entity_id) self.hass.block_till_done() - self.assertTrue(switch.is_on(self.hass)) - self.assertFalse(switch.is_on(self.hass, self.switch_1.entity_id)) - self.assertTrue(switch.is_on(self.hass, self.switch_2.entity_id)) + assert switch.is_on(self.hass) + assert not switch.is_on(self.hass, self.switch_1.entity_id) + assert switch.is_on(self.hass, self.switch_2.entity_id) # Turn all off common.turn_off(self.hass) self.hass.block_till_done() - self.assertFalse(switch.is_on(self.hass)) - self.assertEqual( - STATE_OFF, - self.hass.states.get(switch.ENTITY_ID_ALL_SWITCHES).state) - self.assertFalse(switch.is_on(self.hass, self.switch_1.entity_id)) - self.assertFalse(switch.is_on(self.hass, self.switch_2.entity_id)) - self.assertFalse(switch.is_on(self.hass, self.switch_3.entity_id)) + assert not switch.is_on(self.hass) + assert STATE_OFF == \ + self.hass.states.get(switch.ENTITY_ID_ALL_SWITCHES).state + assert not switch.is_on(self.hass, self.switch_1.entity_id) + assert not switch.is_on(self.hass, self.switch_2.entity_id) + assert not switch.is_on(self.hass, self.switch_3.entity_id) # Turn all on common.turn_on(self.hass) self.hass.block_till_done() - self.assertTrue(switch.is_on(self.hass)) - self.assertEqual( - STATE_ON, - self.hass.states.get(switch.ENTITY_ID_ALL_SWITCHES).state) - self.assertTrue(switch.is_on(self.hass, self.switch_1.entity_id)) - self.assertTrue(switch.is_on(self.hass, self.switch_2.entity_id)) - self.assertTrue(switch.is_on(self.hass, self.switch_3.entity_id)) + assert switch.is_on(self.hass) + assert STATE_ON == \ + self.hass.states.get(switch.ENTITY_ID_ALL_SWITCHES).state + assert switch.is_on(self.hass, self.switch_1.entity_id) + assert switch.is_on(self.hass, self.switch_2.entity_id) + assert switch.is_on(self.hass, self.switch_3.entity_id) def test_setup_two_platforms(self): """Test with bad configuration.""" @@ -86,12 +83,12 @@ class TestSwitch(unittest.TestCase): loader.set_component(self.hass, 'switch.test2', test_platform) test_platform.init(False) - self.assertTrue(setup_component( + assert setup_component( self.hass, switch.DOMAIN, { switch.DOMAIN: {CONF_PLATFORM: 'test'}, '{} 2'.format(switch.DOMAIN): {CONF_PLATFORM: 'test2'}, } - )) + ) async def test_switch_context(hass): diff --git a/tests/components/switch/test_mfi.py b/tests/components/switch/test_mfi.py index d2bf3c57a..222efee0e 100644 --- a/tests/components/switch/test_mfi.py +++ b/tests/components/switch/test_mfi.py @@ -60,13 +60,13 @@ class TestMfiSwitch(unittest.TestCase): def test_name(self): """Test the name.""" - self.assertEqual(self.port.label, self.switch.name) + assert self.port.label == self.switch.name def test_update(self): """Test update.""" self.switch.update() - self.assertEqual(self.port.refresh.call_count, 1) - self.assertEqual(self.port.refresh.call_args, mock.call()) + assert self.port.refresh.call_count == 1 + assert self.port.refresh.call_args == mock.call() def test_update_with_target_state(self): """Test update with target state.""" @@ -74,39 +74,39 @@ class TestMfiSwitch(unittest.TestCase): self.port.data = {} self.port.data['output'] = 'stale' self.switch.update() - self.assertEqual(1.0, self.port.data['output']) - self.assertEqual(None, self.switch._target_state) + assert 1.0 == self.port.data['output'] + assert self.switch._target_state is None self.port.data['output'] = 'untouched' self.switch.update() - self.assertEqual('untouched', self.port.data['output']) + assert 'untouched' == self.port.data['output'] def test_turn_on(self): """Test turn_on.""" self.switch.turn_on() - self.assertEqual(self.port.control.call_count, 1) - self.assertEqual(self.port.control.call_args, mock.call(True)) - self.assertTrue(self.switch._target_state) + assert self.port.control.call_count == 1 + assert self.port.control.call_args == mock.call(True) + assert self.switch._target_state def test_turn_off(self): """Test turn_off.""" self.switch.turn_off() - self.assertEqual(self.port.control.call_count, 1) - self.assertEqual(self.port.control.call_args, mock.call(False)) - self.assertFalse(self.switch._target_state) + assert self.port.control.call_count == 1 + assert self.port.control.call_args == mock.call(False) + assert not self.switch._target_state def test_current_power_w(self): """Test current power.""" self.port.data = {'active_pwr': 10} - self.assertEqual(10, self.switch.current_power_w) + assert 10 == self.switch.current_power_w def test_current_power_w_no_data(self): """Test current power if there is no data.""" self.port.data = {'notpower': 123} - self.assertEqual(0, self.switch.current_power_w) + assert 0 == self.switch.current_power_w def test_device_state_attributes(self): """Test the state attributes.""" self.port.data = {'v_rms': 1.25, 'i_rms': 2.75} - self.assertEqual({'volts': 1.2, 'amps': 2.8}, - self.switch.device_state_attributes) + assert {'volts': 1.2, 'amps': 2.8} == \ + self.switch.device_state_attributes diff --git a/tests/components/switch/test_mochad.py b/tests/components/switch/test_mochad.py index bfbd67e6b..76640f887 100644 --- a/tests/components/switch/test_mochad.py +++ b/tests/components/switch/test_mochad.py @@ -51,7 +51,7 @@ class TestMochadSwitchSetup(unittest.TestCase): ], } } - self.assertTrue(setup_component(self.hass, switch.DOMAIN, good_config)) + assert setup_component(self.hass, switch.DOMAIN, good_config) class TestMochadSwitch(unittest.TestCase): @@ -71,7 +71,7 @@ class TestMochadSwitch(unittest.TestCase): def test_name(self): """Test the name.""" - self.assertEqual('fake_switch', self.switch.name) + assert 'fake_switch' == self.switch.name def test_turn_on(self): """Test turn_on.""" diff --git a/tests/components/switch/test_mqtt.py b/tests/components/switch/test_mqtt.py index 3552ec0dc..5cdd7d230 100644 --- a/tests/components/switch/test_mqtt.py +++ b/tests/components/switch/test_mqtt.py @@ -42,20 +42,20 @@ class TestSwitchMQTT(unittest.TestCase): }) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'state-topic', '1') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state fire_mqtt_message(self.hass, 'state-topic', '0') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state def test_sending_mqtt_commands_and_optimistic(self): """Test the sending MQTT commands in optimistic mode.""" @@ -75,8 +75,8 @@ class TestSwitchMQTT(unittest.TestCase): }) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) - self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_ON == state.state + assert state.attributes.get(ATTR_ASSUMED_STATE) common.turn_on(self.hass, 'switch.test') self.hass.block_till_done() @@ -85,7 +85,7 @@ class TestSwitchMQTT(unittest.TestCase): 'command-topic', 'beer on', 2, False) self.mock_publish.async_publish.reset_mock() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state common.turn_off(self.hass, 'switch.test') self.hass.block_till_done() @@ -93,7 +93,7 @@ class TestSwitchMQTT(unittest.TestCase): self.mock_publish.async_publish.assert_called_once_with( 'command-topic', 'beer off', 2, False) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state def test_controlling_state_via_topic_and_json_message(self): """Test the controlling state via topic and JSON message.""" @@ -110,19 +110,19 @@ class TestSwitchMQTT(unittest.TestCase): }) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state fire_mqtt_message(self.hass, 'state-topic', '{"val":"beer on"}') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state fire_mqtt_message(self.hass, 'state-topic', '{"val":"beer off"}') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state def test_controlling_availability(self): """Test the controlling state via topic.""" @@ -141,32 +141,32 @@ class TestSwitchMQTT(unittest.TestCase): }) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability_topic', '1') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'availability_topic', '0') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'state-topic', '1') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability_topic', '1') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state def test_default_availability_payload(self): """Test the availability payload.""" @@ -183,32 +183,32 @@ class TestSwitchMQTT(unittest.TestCase): }) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability_topic', 'online') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'availability_topic', 'offline') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'state-topic', '1') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability_topic', 'online') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state def test_custom_availability_payload(self): """Test the availability payload.""" @@ -227,32 +227,32 @@ class TestSwitchMQTT(unittest.TestCase): }) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability_topic', 'good') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'availability_topic', 'nogood') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'state-topic', '1') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability_topic', 'good') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state def test_custom_state_payload(self): """Test the state payload.""" @@ -270,20 +270,20 @@ class TestSwitchMQTT(unittest.TestCase): }) state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) - self.assertFalse(state.attributes.get(ATTR_ASSUMED_STATE)) + assert STATE_OFF == state.state + assert not state.attributes.get(ATTR_ASSUMED_STATE) fire_mqtt_message(self.hass, 'state-topic', 'HIGH') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state fire_mqtt_message(self.hass, 'state-topic', 'LOW') self.hass.block_till_done() state = self.hass.states.get('switch.test') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state async def test_unique_id(hass): diff --git a/tests/components/switch/test_rfxtrx.py b/tests/components/switch/test_rfxtrx.py index ae242a1da..ca59f9c9a 100644 --- a/tests/components/switch/test_rfxtrx.py +++ b/tests/components/switch/test_rfxtrx.py @@ -28,29 +28,29 @@ class TestSwitchRfxtrx(unittest.TestCase): def test_valid_config(self): """Test configuration.""" - self.assertTrue(setup_component(self.hass, 'switch', { + assert setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'0b1100cd0213c7f210010f51': { 'name': 'Test', rfxtrx_core.ATTR_FIREEVENT: True} - }}})) + }}}) def test_valid_config_int_device_id(self): """Test configuration.""" - self.assertTrue(setup_component(self.hass, 'switch', { + assert setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {710000141010170: { 'name': 'Test', rfxtrx_core.ATTR_FIREEVENT: True} - }}})) + }}}) def test_invalid_config1(self): """Test invalid configuration.""" - self.assertFalse(setup_component(self.hass, 'switch', { + assert not setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': @@ -58,11 +58,11 @@ class TestSwitchRfxtrx(unittest.TestCase): 'name': 'Test', 'packetid': '0b1100cd0213c7f210010f51', 'signal_repetitions': 3} - }}})) + }}}) def test_invalid_config2(self): """Test invalid configuration.""" - self.assertFalse(setup_component(self.hass, 'switch', { + assert not setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'automatic_add': True, 'invalid_key': 'afda', @@ -71,11 +71,11 @@ class TestSwitchRfxtrx(unittest.TestCase): 'name': 'Test', 'packetid': '0b1100cd0213c7f210010f51', rfxtrx_core.ATTR_FIREEVENT: True} - }}})) + }}}) def test_invalid_config3(self): """Test invalid configuration.""" - self.assertFalse(setup_component(self.hass, 'switch', { + assert not setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': @@ -83,96 +83,96 @@ class TestSwitchRfxtrx(unittest.TestCase): 'name': 'Test', 'packetid': 'AA1100cd0213c7f210010f51', rfxtrx_core.ATTR_FIREEVENT: True} - }}})) + }}}) def test_invalid_config4(self): """Test configuration.""" - self.assertFalse(setup_component(self.hass, 'switch', { + assert not setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'213c7f216': { 'name': 'Test', rfxtrx_core.ATTR_FIREEVENT: True} - }}})) + }}}) def test_default_config(self): """Test with 0 switches.""" - self.assertTrue(setup_component(self.hass, 'switch', { + assert setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'devices': - {}}})) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + {}}}) + assert 0 == len(rfxtrx_core.RFX_DEVICES) def test_old_config(self): """Test with 1 switch.""" - self.assertTrue(setup_component(self.hass, 'switch', { + assert setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'devices': {'123efab1': { 'name': 'Test', - 'packetid': '0b1100cd0213c7f210010f51'}}}})) + 'packetid': '0b1100cd0213c7f210010f51'}}}}) import RFXtrx as rfxtrxmod rfxtrx_core.RFXOBJECT =\ rfxtrxmod.Core("", transport_protocol=rfxtrxmod.DummyTransport) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) entity = rfxtrx_core.RFX_DEVICES['213c7f216'] - self.assertEqual('Test', entity.name) - self.assertEqual('off', entity.state) - self.assertTrue(entity.assumed_state) - self.assertEqual(entity.signal_repetitions, 1) - self.assertFalse(entity.should_fire_event) - self.assertFalse(entity.should_poll) + assert 'Test' == entity.name + assert 'off' == entity.state + assert entity.assumed_state + assert entity.signal_repetitions == 1 + assert not entity.should_fire_event + assert not entity.should_poll - self.assertFalse(entity.is_on) + assert not entity.is_on entity.turn_on() - self.assertTrue(entity.is_on) + assert entity.is_on entity.turn_off() - self.assertFalse(entity.is_on) + assert not entity.is_on def test_one_switch(self): """Test with 1 switch.""" - self.assertTrue(setup_component(self.hass, 'switch', { + assert setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'devices': {'0b1100cd0213c7f210010f51': { - 'name': 'Test'}}}})) + 'name': 'Test'}}}}) import RFXtrx as rfxtrxmod rfxtrx_core.RFXOBJECT =\ rfxtrxmod.Core("", transport_protocol=rfxtrxmod.DummyTransport) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) entity = rfxtrx_core.RFX_DEVICES['213c7f216'] - self.assertEqual('Test', entity.name) - self.assertEqual('off', entity.state) - self.assertTrue(entity.assumed_state) - self.assertEqual(entity.signal_repetitions, 1) - self.assertFalse(entity.should_fire_event) - self.assertFalse(entity.should_poll) + assert 'Test' == entity.name + assert 'off' == entity.state + assert entity.assumed_state + assert entity.signal_repetitions == 1 + assert not entity.should_fire_event + assert not entity.should_poll - self.assertFalse(entity.is_on) + assert not entity.is_on entity.turn_on() - self.assertTrue(entity.is_on) + assert entity.is_on entity.turn_off() - self.assertFalse(entity.is_on) + assert not entity.is_on entity_id = rfxtrx_core.RFX_DEVICES['213c7f216'].entity_id entity_hass = self.hass.states.get(entity_id) - self.assertEqual('Test', entity_hass.name) - self.assertEqual('off', entity_hass.state) + assert 'Test' == entity_hass.name + assert 'off' == entity_hass.state entity.turn_on() entity_hass = self.hass.states.get(entity_id) - self.assertEqual('on', entity_hass.state) + assert 'on' == entity_hass.state entity.turn_off() entity_hass = self.hass.states.get(entity_id) - self.assertEqual('off', entity_hass.state) + assert 'off' == entity_hass.state def test_several_switches(self): """Test with 3 switches.""" - self.assertTrue(setup_component(self.hass, 'switch', { + assert setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'signal_repetitions': 3, 'devices': @@ -181,34 +181,34 @@ class TestSwitchRfxtrx(unittest.TestCase): '0b1100100118cdea02010f70': { 'name': 'Bath'}, '0b1100101118cdea02010f70': { - 'name': 'Living'}}}})) + 'name': 'Living'}}}}) - self.assertEqual(3, len(rfxtrx_core.RFX_DEVICES)) + assert 3 == len(rfxtrx_core.RFX_DEVICES) device_num = 0 for id in rfxtrx_core.RFX_DEVICES: entity = rfxtrx_core.RFX_DEVICES[id] - self.assertEqual(entity.signal_repetitions, 3) + assert entity.signal_repetitions == 3 if entity.name == 'Living': device_num = device_num + 1 - self.assertEqual('off', entity.state) - self.assertEqual('', entity.__str__()) + assert 'off' == entity.state + assert '' == entity.__str__() elif entity.name == 'Bath': device_num = device_num + 1 - self.assertEqual('off', entity.state) - self.assertEqual('', entity.__str__()) + assert 'off' == entity.state + assert '' == entity.__str__() elif entity.name == 'Test': device_num = device_num + 1 - self.assertEqual('off', entity.state) - self.assertEqual('', entity.__str__()) + assert 'off' == entity.state + assert '' == entity.__str__() - self.assertEqual(3, device_num) + assert 3 == device_num def test_discover_switch(self): """Test with discovery of switches.""" - self.assertTrue(setup_component(self.hass, 'switch', { + assert setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'automatic_add': True, - 'devices': {}}})) + 'devices': {}}}) event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') event.data = bytearray([0x0b, 0x11, 0x00, 0x10, 0x01, 0x18, @@ -216,12 +216,12 @@ class TestSwitchRfxtrx(unittest.TestCase): rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) entity = rfxtrx_core.RFX_DEVICES['118cdea2'] - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) - self.assertEqual('', - entity.__str__()) + assert 1 == len(rfxtrx_core.RFX_DEVICES) + assert '' == \ + entity.__str__() rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) + assert 1 == len(rfxtrx_core.RFX_DEVICES) event = rfxtrx_core.get_rfx_object('0b1100100118cdeb02010f70') event.data = bytearray([0x0b, 0x11, 0x00, 0x12, 0x01, 0x18, @@ -229,70 +229,70 @@ class TestSwitchRfxtrx(unittest.TestCase): rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) entity = rfxtrx_core.RFX_DEVICES['118cdeb2'] - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) - self.assertEqual('', - entity.__str__()) + assert 2 == len(rfxtrx_core.RFX_DEVICES) + assert '' == \ + entity.__str__() # Trying to add a sensor event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray(b'\nR\x08^\x07\x01\x00\xb3\x1b\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a light event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') event.data = bytearray([0x0b, 0x11, 0x11, 0x10, 0x01, 0x18, 0xcd, 0xea, 0x01, 0x02, 0x0f, 0x70]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a rollershutter event = rfxtrx_core.get_rfx_object('0a1400adf394ab020e0060') event.data = bytearray([0x0A, 0x14, 0x00, 0xAD, 0xF3, 0x94, 0xAB, 0x02, 0x0E, 0x00, 0x60]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) + assert 2 == len(rfxtrx_core.RFX_DEVICES) def test_discover_switch_noautoadd(self): """Test with discovery of switch when auto add is False.""" - self.assertTrue(setup_component(self.hass, 'switch', { + assert setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'automatic_add': False, - 'devices': {}}})) + 'devices': {}}}) event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') event.data = bytearray([0x0b, 0x11, 0x00, 0x10, 0x01, 0x18, 0xcd, 0xea, 0x01, 0x01, 0x0f, 0x70]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) + assert 0 == len(rfxtrx_core.RFX_DEVICES) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) event = rfxtrx_core.get_rfx_object('0b1100100118cdeb02010f70') event.data = bytearray([0x0b, 0x11, 0x00, 0x12, 0x01, 0x18, 0xcd, 0xea, 0x02, 0x00, 0x00, 0x70]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a sensor event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray(b'\nR\x08^\x07\x01\x00\xb3\x1b\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a light event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') event.data = bytearray([0x0b, 0x11, 0x11, 0x10, 0x01, 0x18, 0xcd, 0xea, 0x01, 0x02, 0x0f, 0x70]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) # Trying to add a rollershutter event = rfxtrx_core.get_rfx_object('0a1400adf394ab020e0060') event.data = bytearray([0x0A, 0x14, 0x00, 0xAD, 0xF3, 0x94, 0xAB, 0x02, 0x0E, 0x00, 0x60]) rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) - self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) + assert 0 == len(rfxtrx_core.RFX_DEVICES) diff --git a/tests/components/switch/test_vultr.py b/tests/components/switch/test_vultr.py index ce8740e9b..699da3431 100644 --- a/tests/components/switch/test_vultr.py +++ b/tests/components/switch/test_vultr.py @@ -74,59 +74,59 @@ class TestVultrSwitchSetup(unittest.TestCase): self.add_entities, None) - self.assertEqual(len(self.DEVICES), 3) + assert len(self.DEVICES) == 3 tested = 0 for device in self.DEVICES: if device.subscription == '555555': - self.assertEqual('Vultr {}', device.name) + assert 'Vultr {}' == device.name tested += 1 device.update() device_attrs = device.device_state_attributes if device.subscription == '555555': - self.assertEqual('Vultr Another Server', device.name) + assert 'Vultr Another Server' == device.name tested += 1 if device.name == 'A Server': - self.assertEqual(True, device.is_on) - self.assertEqual('on', device.state) - self.assertEqual('mdi:server', device.icon) - self.assertEqual('1000', - device_attrs[ATTR_ALLOWED_BANDWIDTH]) - self.assertEqual('yes', - device_attrs[ATTR_AUTO_BACKUPS]) - self.assertEqual('123.123.123.123', - device_attrs[ATTR_IPV4_ADDRESS]) - self.assertEqual('10.05', - device_attrs[ATTR_COST_PER_MONTH]) - self.assertEqual('2013-12-19 14:45:41', - device_attrs[ATTR_CREATED_AT]) - self.assertEqual('576965', - device_attrs[ATTR_SUBSCRIPTION_ID]) + assert device.is_on is True + assert 'on' == device.state + assert 'mdi:server' == device.icon + assert '1000' == \ + device_attrs[ATTR_ALLOWED_BANDWIDTH] + assert 'yes' == \ + device_attrs[ATTR_AUTO_BACKUPS] + assert '123.123.123.123' == \ + device_attrs[ATTR_IPV4_ADDRESS] + assert '10.05' == \ + device_attrs[ATTR_COST_PER_MONTH] + assert '2013-12-19 14:45:41' == \ + device_attrs[ATTR_CREATED_AT] + assert '576965' == \ + device_attrs[ATTR_SUBSCRIPTION_ID] tested += 1 elif device.name == 'Failed Server': - self.assertEqual(False, device.is_on) - self.assertEqual('off', device.state) - self.assertEqual('mdi:server-off', device.icon) - self.assertEqual('1000', - device_attrs[ATTR_ALLOWED_BANDWIDTH]) - self.assertEqual('no', - device_attrs[ATTR_AUTO_BACKUPS]) - self.assertEqual('192.168.100.50', - device_attrs[ATTR_IPV4_ADDRESS]) - self.assertEqual('73.25', - device_attrs[ATTR_COST_PER_MONTH]) - self.assertEqual('2014-10-13 14:45:41', - device_attrs[ATTR_CREATED_AT]) - self.assertEqual('123456', - device_attrs[ATTR_SUBSCRIPTION_ID]) + assert device.is_on is False + assert 'off' == device.state + assert 'mdi:server-off' == device.icon + assert '1000' == \ + device_attrs[ATTR_ALLOWED_BANDWIDTH] + assert 'no' == \ + device_attrs[ATTR_AUTO_BACKUPS] + assert '192.168.100.50' == \ + device_attrs[ATTR_IPV4_ADDRESS] + assert '73.25' == \ + device_attrs[ATTR_COST_PER_MONTH] + assert '2014-10-13 14:45:41' == \ + device_attrs[ATTR_CREATED_AT] + assert '123456' == \ + device_attrs[ATTR_SUBSCRIPTION_ID] tested += 1 - self.assertEqual(4, tested) + assert 4 == tested @requests_mock.Mocker() def test_turn_on(self, mock): @@ -140,7 +140,7 @@ class TestVultrSwitchSetup(unittest.TestCase): device.turn_on() # Turn on - self.assertEqual(1, mock_start.call_count) + assert 1 == mock_start.call_count @requests_mock.Mocker() def test_turn_off(self, mock): @@ -154,7 +154,7 @@ class TestVultrSwitchSetup(unittest.TestCase): device.turn_off() # Turn off - self.assertEqual(1, mock_halt.call_count) + assert 1 == mock_halt.call_count def test_invalid_switch_config(self): """Test config type failures.""" @@ -184,7 +184,7 @@ class TestVultrSwitchSetup(unittest.TestCase): self.add_entities, None) - self.assertIsNotNone(no_subs_setup) + assert no_subs_setup is not None bad_conf = { CONF_NAME: "Missing Server", @@ -196,4 +196,4 @@ class TestVultrSwitchSetup(unittest.TestCase): self.add_entities, None) - self.assertIsNotNone(wrong_subs_setup) + assert wrong_subs_setup is not None diff --git a/tests/components/switch/test_wake_on_lan.py b/tests/components/switch/test_wake_on_lan.py index 42ebd1ff2..c3f4e0405 100644 --- a/tests/components/switch/test_wake_on_lan.py +++ b/tests/components/switch/test_wake_on_lan.py @@ -47,16 +47,16 @@ class TestWOLSwitch(unittest.TestCase): """Test with valid hostname.""" global TEST_STATE TEST_STATE = False - self.assertTrue(setup_component(self.hass, switch.DOMAIN, { + assert setup_component(self.hass, switch.DOMAIN, { 'switch': { 'platform': 'wake_on_lan', 'mac_address': '00-01-02-03-04-05', 'host': 'validhostname', } - })) + }) state = self.hass.states.get('switch.wake_on_lan') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state TEST_STATE = True @@ -64,13 +64,13 @@ class TestWOLSwitch(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('switch.wake_on_lan') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state common.turn_off(self.hass, 'switch.wake_on_lan') self.hass.block_till_done() state = self.hass.states.get('switch.wake_on_lan') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state @patch('wakeonlan.send_magic_packet', new=send_magic_packet) @patch('subprocess.call', new=call) @@ -79,16 +79,16 @@ class TestWOLSwitch(unittest.TestCase): """Test with valid hostname on windows.""" global TEST_STATE TEST_STATE = False - self.assertTrue(setup_component(self.hass, switch.DOMAIN, { + assert setup_component(self.hass, switch.DOMAIN, { 'switch': { 'platform': 'wake_on_lan', 'mac_address': '00-01-02-03-04-05', 'host': 'validhostname', } - })) + }) state = self.hass.states.get('switch.wake_on_lan') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state TEST_STATE = True @@ -96,33 +96,33 @@ class TestWOLSwitch(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('switch.wake_on_lan') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state @patch('wakeonlan.send_magic_packet', new=send_magic_packet) @patch('subprocess.call', new=call) def test_minimal_config(self): """Test with minimal config.""" - self.assertTrue(setup_component(self.hass, switch.DOMAIN, { + assert setup_component(self.hass, switch.DOMAIN, { 'switch': { 'platform': 'wake_on_lan', 'mac_address': '00-01-02-03-04-05', } - })) + }) @patch('wakeonlan.send_magic_packet', new=send_magic_packet) @patch('subprocess.call', new=call) def test_broadcast_config(self): """Test with broadcast address config.""" - self.assertTrue(setup_component(self.hass, switch.DOMAIN, { + assert setup_component(self.hass, switch.DOMAIN, { 'switch': { 'platform': 'wake_on_lan', 'mac_address': '00-01-02-03-04-05', 'broadcast_address': '255.255.255.255', } - })) + }) state = self.hass.states.get('switch.wake_on_lan') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state common.turn_on(self.hass, 'switch.wake_on_lan') self.hass.block_till_done() @@ -133,7 +133,7 @@ class TestWOLSwitch(unittest.TestCase): """Test with turn off script.""" global TEST_STATE TEST_STATE = False - self.assertTrue(setup_component(self.hass, switch.DOMAIN, { + assert setup_component(self.hass, switch.DOMAIN, { 'switch': { 'platform': 'wake_on_lan', 'mac_address': '00-01-02-03-04-05', @@ -142,11 +142,11 @@ class TestWOLSwitch(unittest.TestCase): 'service': 'shell_command.turn_off_TARGET', }, } - })) + }) calls = mock_service(self.hass, 'shell_command', 'turn_off_TARGET') state = self.hass.states.get('switch.wake_on_lan') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state TEST_STATE = True @@ -154,7 +154,7 @@ class TestWOLSwitch(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('switch.wake_on_lan') - self.assertEqual(STATE_ON, state.state) + assert STATE_ON == state.state assert len(calls) == 0 TEST_STATE = False @@ -163,7 +163,7 @@ class TestWOLSwitch(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('switch.wake_on_lan') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state assert len(calls) == 1 @patch('wakeonlan.send_magic_packet', new=send_magic_packet) @@ -173,16 +173,16 @@ class TestWOLSwitch(unittest.TestCase): """Test with invalid hostname on windows.""" global TEST_STATE TEST_STATE = False - self.assertTrue(setup_component(self.hass, switch.DOMAIN, { + assert setup_component(self.hass, switch.DOMAIN, { 'switch': { 'platform': 'wake_on_lan', 'mac_address': '00-01-02-03-04-05', 'host': 'invalidhostname', } - })) + }) state = self.hass.states.get('switch.wake_on_lan') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state TEST_STATE = True @@ -190,4 +190,4 @@ class TestWOLSwitch(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('switch.wake_on_lan') - self.assertEqual(STATE_OFF, state.state) + assert STATE_OFF == state.state diff --git a/tests/components/test_alert.py b/tests/components/test_alert.py index 44ece2fc3..d7aaa3dd0 100644 --- a/tests/components/test_alert.py +++ b/tests/components/test_alert.py @@ -106,22 +106,22 @@ class TestAlert(unittest.TestCase): """Test is_on method.""" self.hass.states.set(ENTITY_ID, STATE_ON) self.hass.block_till_done() - self.assertTrue(alert.is_on(self.hass, ENTITY_ID)) + assert alert.is_on(self.hass, ENTITY_ID) self.hass.states.set(ENTITY_ID, STATE_OFF) self.hass.block_till_done() - self.assertFalse(alert.is_on(self.hass, ENTITY_ID)) + assert not alert.is_on(self.hass, ENTITY_ID) def test_setup(self): """Test setup method.""" assert setup_component(self.hass, alert.DOMAIN, TEST_CONFIG) - self.assertEqual(STATE_IDLE, self.hass.states.get(ENTITY_ID).state) + assert STATE_IDLE == self.hass.states.get(ENTITY_ID).state def test_fire(self): """Test the alert firing.""" assert setup_component(self.hass, alert.DOMAIN, TEST_CONFIG) self.hass.states.set("sensor.test", STATE_ON) self.hass.block_till_done() - self.assertEqual(STATE_ON, self.hass.states.get(ENTITY_ID).state) + assert STATE_ON == self.hass.states.get(ENTITY_ID).state def test_silence(self): """Test silencing the alert.""" @@ -130,15 +130,15 @@ class TestAlert(unittest.TestCase): self.hass.block_till_done() turn_off(self.hass, ENTITY_ID) self.hass.block_till_done() - self.assertEqual(STATE_OFF, self.hass.states.get(ENTITY_ID).state) + assert STATE_OFF == self.hass.states.get(ENTITY_ID).state # alert should not be silenced on next fire self.hass.states.set("sensor.test", STATE_OFF) self.hass.block_till_done() - self.assertEqual(STATE_IDLE, self.hass.states.get(ENTITY_ID).state) + assert STATE_IDLE == self.hass.states.get(ENTITY_ID).state self.hass.states.set("sensor.test", STATE_ON) self.hass.block_till_done() - self.assertEqual(STATE_ON, self.hass.states.get(ENTITY_ID).state) + assert STATE_ON == self.hass.states.get(ENTITY_ID).state def test_reset(self): """Test resetting the alert.""" @@ -147,38 +147,38 @@ class TestAlert(unittest.TestCase): self.hass.block_till_done() turn_off(self.hass, ENTITY_ID) self.hass.block_till_done() - self.assertEqual(STATE_OFF, self.hass.states.get(ENTITY_ID).state) + assert STATE_OFF == self.hass.states.get(ENTITY_ID).state turn_on(self.hass, ENTITY_ID) self.hass.block_till_done() - self.assertEqual(STATE_ON, self.hass.states.get(ENTITY_ID).state) + assert STATE_ON == self.hass.states.get(ENTITY_ID).state def test_toggle(self): """Test toggling alert.""" assert setup_component(self.hass, alert.DOMAIN, TEST_CONFIG) self.hass.states.set("sensor.test", STATE_ON) self.hass.block_till_done() - self.assertEqual(STATE_ON, self.hass.states.get(ENTITY_ID).state) + assert STATE_ON == self.hass.states.get(ENTITY_ID).state toggle(self.hass, ENTITY_ID) self.hass.block_till_done() - self.assertEqual(STATE_OFF, self.hass.states.get(ENTITY_ID).state) + assert STATE_OFF == self.hass.states.get(ENTITY_ID).state toggle(self.hass, ENTITY_ID) self.hass.block_till_done() - self.assertEqual(STATE_ON, self.hass.states.get(ENTITY_ID).state) + assert STATE_ON == self.hass.states.get(ENTITY_ID).state def test_hidden(self): """Test entity hiding.""" assert setup_component(self.hass, alert.DOMAIN, TEST_CONFIG) hidden = self.hass.states.get(ENTITY_ID).attributes.get('hidden') - self.assertTrue(hidden) + assert hidden self.hass.states.set("sensor.test", STATE_ON) self.hass.block_till_done() hidden = self.hass.states.get(ENTITY_ID).attributes.get('hidden') - self.assertFalse(hidden) + assert not hidden turn_off(self.hass, ENTITY_ID) hidden = self.hass.states.get(ENTITY_ID).attributes.get('hidden') - self.assertFalse(hidden) + assert not hidden def test_notification_no_done_message(self): """Test notifications.""" @@ -195,15 +195,15 @@ class TestAlert(unittest.TestCase): notify.DOMAIN, NOTIFIER, record_event) assert setup_component(self.hass, alert.DOMAIN, config) - self.assertEqual(0, len(events)) + assert 0 == len(events) self.hass.states.set("sensor.test", STATE_ON) self.hass.block_till_done() - self.assertEqual(1, len(events)) + assert 1 == len(events) self.hass.states.set("sensor.test", STATE_OFF) self.hass.block_till_done() - self.assertEqual(1, len(events)) + assert 1 == len(events) def test_notification(self): """Test notifications.""" @@ -218,15 +218,15 @@ class TestAlert(unittest.TestCase): notify.DOMAIN, NOTIFIER, record_event) assert setup_component(self.hass, alert.DOMAIN, TEST_CONFIG) - self.assertEqual(0, len(events)) + assert 0 == len(events) self.hass.states.set("sensor.test", STATE_ON) self.hass.block_till_done() - self.assertEqual(1, len(events)) + assert 1 == len(events) self.hass.states.set("sensor.test", STATE_OFF) self.hass.block_till_done() - self.assertEqual(2, len(events)) + assert 2 == len(events) def test_skipfirst(self): """Test skipping first notification.""" @@ -243,11 +243,11 @@ class TestAlert(unittest.TestCase): notify.DOMAIN, NOTIFIER, record_event) assert setup_component(self.hass, alert.DOMAIN, config) - self.assertEqual(0, len(events)) + assert 0 == len(events) self.hass.states.set("sensor.test", STATE_ON) self.hass.block_till_done() - self.assertEqual(0, len(events)) + assert 0 == len(events) def test_noack(self): """Test no ack feature.""" @@ -255,7 +255,7 @@ class TestAlert(unittest.TestCase): self.hass.add_job(entity.begin_alerting) self.hass.block_till_done() - self.assertEqual(True, entity.hidden) + assert entity.hidden is True def test_done_message_state_tracker_reset_on_cancel(self): """Test that the done message is reset when canceled.""" diff --git a/tests/components/test_canary.py b/tests/components/test_canary.py index 310f3be9f..463d72291 100644 --- a/tests/components/test_canary.py +++ b/tests/components/test_canary.py @@ -60,8 +60,7 @@ class TestCanary(unittest.TestCase): } } - self.assertTrue( - setup.setup_component(self.hass, canary.DOMAIN, config)) + assert setup.setup_component(self.hass, canary.DOMAIN, config) mock_update.assert_called_once_with() mock_login.assert_called_once_with() @@ -74,8 +73,7 @@ class TestCanary(unittest.TestCase): } } - self.assertFalse( - setup.setup_component(self.hass, canary.DOMAIN, config)) + assert not setup.setup_component(self.hass, canary.DOMAIN, config) def test_setup_with_missing_username(self): """Test setup component.""" @@ -85,5 +83,4 @@ class TestCanary(unittest.TestCase): } } - self.assertFalse( - setup.setup_component(self.hass, canary.DOMAIN, config)) + assert not setup.setup_component(self.hass, canary.DOMAIN, config) diff --git a/tests/components/test_configurator.py b/tests/components/test_configurator.py index 22f0d6646..44ef592bc 100644 --- a/tests/components/test_configurator.py +++ b/tests/components/test_configurator.py @@ -26,19 +26,19 @@ class TestConfigurator(unittest.TestCase): request_id = configurator.request_config( self.hass, "Test Request", lambda _: None) - self.assertEqual( - 1, len(self.hass.services.services.get(configurator.DOMAIN, [])), - "No new service registered") + assert 1 == \ + len(self.hass.services.services.get(configurator.DOMAIN, [])), \ + "No new service registered" states = self.hass.states.all() - self.assertEqual(1, len(states), "Expected a new state registered") + assert 1 == len(states), "Expected a new state registered" state = states[0] - self.assertEqual(configurator.STATE_CONFIGURE, state.state) - self.assertEqual( - request_id, state.attributes.get(configurator.ATTR_CONFIGURE_ID)) + assert configurator.STATE_CONFIGURE == state.state + assert \ + request_id == state.attributes.get(configurator.ATTR_CONFIGURE_ID) def test_request_all_info(self): """Test request config with all possible info.""" @@ -67,10 +67,10 @@ class TestConfigurator(unittest.TestCase): } states = self.hass.states.all() - self.assertEqual(1, len(states)) + assert 1 == len(states) state = states[0] - self.assertEqual(configurator.STATE_CONFIGURE, state.state) + assert configurator.STATE_CONFIGURE == state.state assert exp_attr == state.attributes def test_callback_called_on_configure(self): @@ -84,7 +84,7 @@ class TestConfigurator(unittest.TestCase): {configurator.ATTR_CONFIGURE_ID: request_id}) self.hass.block_till_done() - self.assertEqual(1, len(calls), "Callback not called") + assert 1 == len(calls), "Callback not called" def test_state_change_on_notify_errors(self): """Test state change on notify errors.""" @@ -94,7 +94,7 @@ class TestConfigurator(unittest.TestCase): configurator.notify_errors(self.hass, request_id, error) state = self.hass.states.all()[0] - self.assertEqual(error, state.attributes.get(configurator.ATTR_ERRORS)) + assert error == state.attributes.get(configurator.ATTR_ERRORS) def test_notify_errors_fail_silently_on_bad_request_id(self): """Test if notify errors fails silently with a bad request id.""" @@ -105,11 +105,11 @@ class TestConfigurator(unittest.TestCase): request_id = configurator.request_config( self.hass, "Test Request", lambda _: None) configurator.request_done(self.hass, request_id) - self.assertEqual(1, len(self.hass.states.all())) + assert 1 == len(self.hass.states.all()) self.hass.bus.fire(EVENT_TIME_CHANGED) self.hass.block_till_done() - self.assertEqual(0, len(self.hass.states.all())) + assert 0 == len(self.hass.states.all()) def test_request_done_fail_silently_on_bad_request_id(self): """Test that request_done fails silently with a bad request id.""" diff --git a/tests/components/test_datadog.py b/tests/components/test_datadog.py index f9724989f..eb7bff23b 100644 --- a/tests/components/test_datadog.py +++ b/tests/components/test_datadog.py @@ -51,17 +51,15 @@ class TestDatadog(unittest.TestCase): } }) - self.assertEqual(mock_connection.call_count, 1) - self.assertEqual( - mock_connection.call_args, + assert mock_connection.call_count == 1 + assert mock_connection.call_args == \ mock.call(statsd_host='host', statsd_port=123) - ) - self.assertTrue(self.hass.bus.listen.called) - self.assertEqual(EVENT_LOGBOOK_ENTRY, - self.hass.bus.listen.call_args_list[0][0][0]) - self.assertEqual(EVENT_STATE_CHANGED, - self.hass.bus.listen.call_args_list[1][0][0]) + assert self.hass.bus.listen.called + assert EVENT_LOGBOOK_ENTRY == \ + self.hass.bus.listen.call_args_list[0][0][0] + assert EVENT_STATE_CHANGED == \ + self.hass.bus.listen.call_args_list[1][0][0] @MockDependency('datadog') def test_datadog_setup_defaults(self, mock_datadog): @@ -77,12 +75,10 @@ class TestDatadog(unittest.TestCase): } }) - self.assertEqual(mock_connection.call_count, 1) - self.assertEqual( - mock_connection.call_args, + assert mock_connection.call_count == 1 + assert mock_connection.call_args == \ mock.call(statsd_host='host', statsd_port=8125) - ) - self.assertTrue(self.hass.bus.listen.called) + assert self.hass.bus.listen.called @MockDependency('datadog') def test_logbook_entry(self, mock_datadog): @@ -97,7 +93,7 @@ class TestDatadog(unittest.TestCase): } }) - self.assertTrue(self.hass.bus.listen.called) + assert self.hass.bus.listen.called handler_method = self.hass.bus.listen.call_args_list[0][0][1] event = { @@ -108,9 +104,8 @@ class TestDatadog(unittest.TestCase): } handler_method(mock.MagicMock(data=event)) - self.assertEqual(mock_client.event.call_count, 1) - self.assertEqual( - mock_client.event.call_args, + assert mock_client.event.call_count == 1 + assert mock_client.event.call_args == \ mock.call( title="Home Assistant", text="%%% \n **{}** {} \n %%%".format( @@ -119,7 +114,6 @@ class TestDatadog(unittest.TestCase): ), tags=["entity:sensor.foo.bar", "domain:automation"] ) - ) mock_client.event.reset_mock() @@ -137,7 +131,7 @@ class TestDatadog(unittest.TestCase): } }) - self.assertTrue(self.hass.bus.listen.called) + assert self.hass.bus.listen.called handler_method = self.hass.bus.listen.call_args_list[1][0][1] valid = { @@ -157,7 +151,7 @@ class TestDatadog(unittest.TestCase): state=in_, attributes=attributes) handler_method(mock.MagicMock(data={'new_state': state})) - self.assertEqual(mock_client.gauge.call_count, 3) + assert mock_client.gauge.call_count == 3 for attribute, value in attributes.items(): mock_client.gauge.assert_has_calls([ @@ -169,16 +163,14 @@ class TestDatadog(unittest.TestCase): ) ]) - self.assertEqual( - mock_client.gauge.call_args, + assert mock_client.gauge.call_args == \ mock.call("ha.sensor", out, sample_rate=1, tags=[ "entity:{}".format(state.entity_id) ]) - ) mock_client.gauge.reset_mock() for invalid in ('foo', '', object): handler_method(mock.MagicMock(data={ 'new_state': ha.State('domain.test', invalid, {})})) - self.assertFalse(mock_client.gauge.called) + assert not mock_client.gauge.called diff --git a/tests/components/test_device_sun_light_trigger.py b/tests/components/test_device_sun_light_trigger.py index 7107eee74..b9f63922b 100644 --- a/tests/components/test_device_sun_light_trigger.py +++ b/tests/components/test_device_sun_light_trigger.py @@ -49,13 +49,13 @@ class TestDeviceSunLightTrigger(unittest.TestCase): 'track': True, 'vendor': None} }): - self.assertTrue(setup_component(self.hass, device_tracker.DOMAIN, { + assert setup_component(self.hass, device_tracker.DOMAIN, { device_tracker.DOMAIN: {CONF_PLATFORM: 'test'} - })) + }) - self.assertTrue(setup_component(self.hass, light.DOMAIN, { + assert setup_component(self.hass, light.DOMAIN, { light.DOMAIN: {CONF_PLATFORM: 'test'} - })) + }) def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" @@ -65,9 +65,9 @@ class TestDeviceSunLightTrigger(unittest.TestCase): """Test lights go on when there is someone home and the sun sets.""" test_time = datetime(2017, 4, 5, 1, 2, 3, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.utcnow', return_value=test_time): - self.assertTrue(setup_component( + assert setup_component( self.hass, device_sun_light_trigger.DOMAIN, { - device_sun_light_trigger.DOMAIN: {}})) + device_sun_light_trigger.DOMAIN: {}}) common_light.turn_off(self.hass) @@ -78,7 +78,7 @@ class TestDeviceSunLightTrigger(unittest.TestCase): fire_time_changed(self.hass, test_time) self.hass.block_till_done() - self.assertTrue(light.is_on(self.hass)) + assert light.is_on(self.hass) def test_lights_turn_off_when_everyone_leaves(self): """Test lights turn off when everyone leaves the house.""" @@ -86,16 +86,16 @@ class TestDeviceSunLightTrigger(unittest.TestCase): self.hass.block_till_done() - self.assertTrue(setup_component( + assert setup_component( self.hass, device_sun_light_trigger.DOMAIN, { - device_sun_light_trigger.DOMAIN: {}})) + device_sun_light_trigger.DOMAIN: {}}) self.hass.states.set(device_tracker.ENTITY_ID_ALL_DEVICES, STATE_NOT_HOME) self.hass.block_till_done() - self.assertFalse(light.is_on(self.hass)) + assert not light.is_on(self.hass) def test_lights_turn_on_when_coming_home_after_sun_set(self): """Test lights turn on when coming home after sun set.""" @@ -104,12 +104,12 @@ class TestDeviceSunLightTrigger(unittest.TestCase): common_light.turn_off(self.hass) self.hass.block_till_done() - self.assertTrue(setup_component( + assert setup_component( self.hass, device_sun_light_trigger.DOMAIN, { - device_sun_light_trigger.DOMAIN: {}})) + device_sun_light_trigger.DOMAIN: {}}) self.hass.states.set( device_tracker.ENTITY_ID_FORMAT.format('device_2'), STATE_HOME) self.hass.block_till_done() - self.assertTrue(light.is_on(self.hass)) + assert light.is_on(self.hass) diff --git a/tests/components/test_dialogflow.py b/tests/components/test_dialogflow.py index 0acf08335..e05e33b30 100644 --- a/tests/components/test_dialogflow.py +++ b/tests/components/test_dialogflow.py @@ -169,8 +169,8 @@ class TestDialogflow(unittest.TestCase): } req = _intent_req(data) - self.assertEqual(200, req.status_code) - self.assertEqual("", req.text) + assert 200 == req.status_code + assert "" == req.text def test_intent_slot_filling(self): """Test when Dialogflow asks for slot-filling return none.""" @@ -238,8 +238,8 @@ class TestDialogflow(unittest.TestCase): } req = _intent_req(data) - self.assertEqual(200, req.status_code) - self.assertEqual("", req.text) + assert 200 == req.status_code + assert "" == req.text def test_intent_request_with_parameters(self): """Test a request with parameters.""" @@ -281,9 +281,9 @@ class TestDialogflow(unittest.TestCase): "originalRequest": None } req = _intent_req(data) - self.assertEqual(200, req.status_code) + assert 200 == req.status_code text = req.json().get("speech") - self.assertEqual("You told us your sign is virgo.", text) + assert "You told us your sign is virgo." == text def test_intent_request_with_parameters_but_empty(self): """Test a request with parameters but empty value.""" @@ -325,9 +325,9 @@ class TestDialogflow(unittest.TestCase): "originalRequest": None } req = _intent_req(data) - self.assertEqual(200, req.status_code) + assert 200 == req.status_code text = req.json().get("speech") - self.assertEqual("You told us your sign is .", text) + assert "You told us your sign is ." == text def test_intent_request_without_slots(self): """Test a request without slots.""" @@ -367,19 +367,19 @@ class TestDialogflow(unittest.TestCase): "originalRequest": None } req = _intent_req(data) - self.assertEqual(200, req.status_code) + assert 200 == req.status_code text = req.json().get("speech") - self.assertEqual("Anne Therese is at unknown and Paulus is at unknown", - text) + assert "Anne Therese is at unknown and Paulus is at unknown" == \ + text hass.states.set("device_tracker.paulus", "home") hass.states.set("device_tracker.anne_therese", "home") req = _intent_req(data) - self.assertEqual(200, req.status_code) + assert 200 == req.status_code text = req.json().get("speech") - self.assertEqual("You are both home, you silly", text) + assert "You are both home, you silly" == text def test_intent_request_calling_service(self): """Test a request for calling a service. @@ -426,13 +426,13 @@ class TestDialogflow(unittest.TestCase): } call_count = len(calls) req = _intent_req(data) - self.assertEqual(200, req.status_code) - self.assertEqual(call_count + 1, len(calls)) + assert 200 == req.status_code + assert call_count + 1 == len(calls) call = calls[-1] - self.assertEqual("test", call.domain) - self.assertEqual("dialogflow", call.service) - self.assertEqual(["switch.test"], call.data.get("entity_id")) - self.assertEqual("virgo", call.data.get("hello")) + assert "test" == call.domain + assert "dialogflow" == call.service + assert ["switch.test"] == call.data.get("entity_id") + assert "virgo" == call.data.get("hello") def test_intent_with_no_action(self): """Test an intent with no defined action.""" @@ -474,10 +474,10 @@ class TestDialogflow(unittest.TestCase): "originalRequest": None } req = _intent_req(data) - self.assertEqual(200, req.status_code) + assert 200 == req.status_code text = req.json().get("speech") - self.assertEqual( - "You have not defined an action in your Dialogflow intent.", text) + assert \ + "You have not defined an action in your Dialogflow intent." == text def test_intent_with_unknown_action(self): """Test an intent with an action not defined in the conf.""" @@ -519,7 +519,7 @@ class TestDialogflow(unittest.TestCase): "originalRequest": None } req = _intent_req(data) - self.assertEqual(200, req.status_code) + assert 200 == req.status_code text = req.json().get("speech") - self.assertEqual( - "This intent is not yet configured within Home Assistant.", text) + assert \ + "This intent is not yet configured within Home Assistant." == text diff --git a/tests/components/test_dyson.py b/tests/components/test_dyson.py index 0352551ae..2e7b05b06 100644 --- a/tests/components/test_dyson.py +++ b/tests/components/test_dyson.py @@ -51,7 +51,7 @@ class DysonTest(unittest.TestCase): dyson.CONF_PASSWORD: "password", dyson.CONF_LANGUAGE: "FR" }}) - self.assertEqual(mocked_login.call_count, 1) + assert mocked_login.call_count == 1 @mock.patch('libpurecoollink.dyson.DysonAccount.devices', return_value=[]) @mock.patch('libpurecoollink.dyson.DysonAccount.login', return_value=True) @@ -62,9 +62,9 @@ class DysonTest(unittest.TestCase): dyson.CONF_PASSWORD: "password", dyson.CONF_LANGUAGE: "FR" }}) - self.assertEqual(mocked_login.call_count, 1) - self.assertEqual(mocked_devices.call_count, 1) - self.assertEqual(len(self.hass.data[dyson.DYSON_DEVICES]), 0) + assert mocked_login.call_count == 1 + assert mocked_devices.call_count == 1 + assert len(self.hass.data[dyson.DYSON_DEVICES]) == 0 @mock.patch('homeassistant.helpers.discovery.load_platform') @mock.patch('libpurecoollink.dyson.DysonAccount.devices', @@ -84,10 +84,10 @@ class DysonTest(unittest.TestCase): } ] }}) - self.assertEqual(mocked_login.call_count, 1) - self.assertEqual(mocked_devices.call_count, 1) - self.assertEqual(len(self.hass.data[dyson.DYSON_DEVICES]), 1) - self.assertEqual(mocked_discovery.call_count, 4) + assert mocked_login.call_count == 1 + assert mocked_devices.call_count == 1 + assert len(self.hass.data[dyson.DYSON_DEVICES]) == 1 + assert mocked_discovery.call_count == 4 @mock.patch('libpurecoollink.dyson.DysonAccount.devices', return_value=[_get_dyson_account_device_not_available()]) @@ -106,9 +106,9 @@ class DysonTest(unittest.TestCase): } ] }}) - self.assertEqual(mocked_login.call_count, 1) - self.assertEqual(mocked_devices.call_count, 1) - self.assertEqual(len(self.hass.data[dyson.DYSON_DEVICES]), 0) + assert mocked_login.call_count == 1 + assert mocked_devices.call_count == 1 + assert len(self.hass.data[dyson.DYSON_DEVICES]) == 0 @mock.patch('libpurecoollink.dyson.DysonAccount.devices', return_value=[_get_dyson_account_device_error()]) @@ -127,9 +127,9 @@ class DysonTest(unittest.TestCase): } ] }}) - self.assertEqual(mocked_login.call_count, 1) - self.assertEqual(mocked_devices.call_count, 1) - self.assertEqual(len(self.hass.data[dyson.DYSON_DEVICES]), 0) + assert mocked_login.call_count == 1 + assert mocked_devices.call_count == 1 + assert len(self.hass.data[dyson.DYSON_DEVICES]) == 0 @mock.patch('homeassistant.helpers.discovery.load_platform') @mock.patch('libpurecoollink.dyson.DysonAccount.devices', @@ -150,10 +150,10 @@ class DysonTest(unittest.TestCase): } ] }}) - self.assertEqual(mocked_login.call_count, 1) - self.assertEqual(mocked_devices.call_count, 1) - self.assertEqual(len(self.hass.data[dyson.DYSON_DEVICES]), 0) - self.assertEqual(mocked_discovery.call_count, 0) + assert mocked_login.call_count == 1 + assert mocked_devices.call_count == 1 + assert len(self.hass.data[dyson.DYSON_DEVICES]) == 0 + assert mocked_discovery.call_count == 0 @mock.patch('homeassistant.helpers.discovery.load_platform') @mock.patch('libpurecoollink.dyson.DysonAccount.devices', @@ -169,10 +169,10 @@ class DysonTest(unittest.TestCase): dyson.CONF_TIMEOUT: 5, dyson.CONF_RETRY: 2 }}) - self.assertEqual(mocked_login.call_count, 1) - self.assertEqual(mocked_devices.call_count, 1) - self.assertEqual(len(self.hass.data[dyson.DYSON_DEVICES]), 1) - self.assertEqual(mocked_discovery.call_count, 4) + assert mocked_login.call_count == 1 + assert mocked_devices.call_count == 1 + assert len(self.hass.data[dyson.DYSON_DEVICES]) == 1 + assert mocked_discovery.call_count == 4 @mock.patch('libpurecoollink.dyson.DysonAccount.devices', return_value=[_get_dyson_account_device_not_available()]) @@ -187,6 +187,6 @@ class DysonTest(unittest.TestCase): dyson.CONF_TIMEOUT: 5, dyson.CONF_RETRY: 2 }}) - self.assertEqual(mocked_login.call_count, 1) - self.assertEqual(mocked_devices.call_count, 1) - self.assertEqual(len(self.hass.data[dyson.DYSON_DEVICES]), 0) + assert mocked_login.call_count == 1 + assert mocked_devices.call_count == 1 + assert len(self.hass.data[dyson.DYSON_DEVICES]) == 0 diff --git a/tests/components/test_feedreader.py b/tests/components/test_feedreader.py index 668f11636..b84f6dd7d 100644 --- a/tests/components/test_feedreader.py +++ b/tests/components/test_feedreader.py @@ -59,8 +59,8 @@ class TestFeedreaderComponent(unittest.TestCase): """Test the general setup of this component.""" with patch("homeassistant.components.feedreader." "track_time_interval") as track_method: - self.assertTrue(setup_component(self.hass, feedreader.DOMAIN, - VALID_CONFIG_1)) + assert setup_component( + self.hass, feedreader.DOMAIN, VALID_CONFIG_1) track_method.assert_called_once_with(self.hass, mock.ANY, DEFAULT_SCAN_INTERVAL) @@ -68,15 +68,14 @@ class TestFeedreaderComponent(unittest.TestCase): """Test the setup of this component with scan interval.""" with patch("homeassistant.components.feedreader." "track_time_interval") as track_method: - self.assertTrue(setup_component(self.hass, feedreader.DOMAIN, - VALID_CONFIG_2)) + assert setup_component( + self.hass, feedreader.DOMAIN, VALID_CONFIG_2) track_method.assert_called_once_with(self.hass, mock.ANY, timedelta(seconds=60)) def test_setup_max_entries(self): """Test the setup of this component with max entries.""" - self.assertTrue(setup_component(self.hass, feedreader.DOMAIN, - VALID_CONFIG_3)) + assert setup_component(self.hass, feedreader.DOMAIN, VALID_CONFIG_3) def setup_manager(self, feed_data, max_entries=DEFAULT_MAX_ENTRIES): """Set up feed manager.""" diff --git a/tests/components/test_google.py b/tests/components/test_google.py index b8dc29b5d..36c4b572b 100644 --- a/tests/components/test_google.py +++ b/tests/components/test_google.py @@ -31,7 +31,7 @@ class TestGoogle(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, 'google', config)) + assert setup_component(self.hass, 'google', config) def test_get_calendar_info(self): """Test getting the calendar info.""" @@ -52,7 +52,7 @@ class TestGoogle(unittest.TestCase): } calendar_info = google.get_calendar_info(self.hass, calendar) - self.assertEqual(calendar_info, { + assert calendar_info == { 'cal_id': 'qwertyuiopasdfghjklzxcvbnm@import.calendar.google.com', 'entities': [{ 'device_id': 'we_are_we_are_a_test_calendar', @@ -60,7 +60,7 @@ class TestGoogle(unittest.TestCase): 'track': True, 'ignore_availability': True, }] - }) + } def test_found_calendar(self): """Test when a calendar is found.""" @@ -85,8 +85,7 @@ class TestGoogle(unittest.TestCase): calendar_service = google.GoogleCalendarService( self.hass.config.path(google.TOKEN_FILE)) - self.assertTrue(google.setup_services(self.hass, True, - calendar_service)) + assert google.setup_services(self.hass, True, calendar_service) # self.hass.services.call('google', 'found_calendar', calendar, # blocking=True) diff --git a/tests/components/test_graphite.py b/tests/components/test_graphite.py index 7ceda9e19..1b96de089 100644 --- a/tests/components/test_graphite.py +++ b/tests/components/test_graphite.py @@ -29,11 +29,9 @@ class TestGraphite(unittest.TestCase): def test_setup(self, mock_socket): """Test setup.""" assert setup_component(self.hass, graphite.DOMAIN, {'graphite': {}}) - self.assertEqual(mock_socket.call_count, 1) - self.assertEqual( - mock_socket.call_args, + assert mock_socket.call_count == 1 + assert mock_socket.call_args == \ mock.call(socket.AF_INET, socket.SOCK_STREAM) - ) @patch('socket.socket') @patch('homeassistant.components.graphite.GraphiteFeeder') @@ -47,16 +45,12 @@ class TestGraphite(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, graphite.DOMAIN, config)) - self.assertEqual(mock_gf.call_count, 1) - self.assertEqual( - mock_gf.call_args, mock.call(self.hass, 'foo', 123, 'me') - ) - self.assertEqual(mock_socket.call_count, 1) - self.assertEqual( - mock_socket.call_args, + assert setup_component(self.hass, graphite.DOMAIN, config) + assert mock_gf.call_count == 1 + assert mock_gf.call_args == mock.call(self.hass, 'foo', 123, 'me') + assert mock_socket.call_count == 1 + assert mock_socket.call_args == \ mock.call(socket.AF_INET, socket.SOCK_STREAM) - ) @patch('socket.socket') @patch('homeassistant.components.graphite.GraphiteFeeder') @@ -69,13 +63,11 @@ class TestGraphite(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, graphite.DOMAIN, config)) - self.assertTrue(mock_gf.called) - self.assertEqual(mock_socket.call_count, 1) - self.assertEqual( - mock_socket.call_args, + assert setup_component(self.hass, graphite.DOMAIN, config) + assert mock_gf.called + assert mock_socket.call_count == 1 + assert mock_socket.call_args == \ mock.call(socket.AF_INET, socket.SOCK_STREAM) - ) def test_subscribe(self): """Test the subscription.""" @@ -85,34 +77,30 @@ class TestGraphite(unittest.TestCase): mock.call(EVENT_HOMEASSISTANT_START, gf.start_listen), mock.call(EVENT_HOMEASSISTANT_STOP, gf.shutdown), ]) - self.assertEqual(fake_hass.bus.listen.call_count, 1) - self.assertEqual( - fake_hass.bus.listen.call_args, + assert fake_hass.bus.listen.call_count == 1 + assert fake_hass.bus.listen.call_args == \ mock.call(EVENT_STATE_CHANGED, gf.event_listener) - ) def test_start(self): """Test the start.""" with mock.patch.object(self.gf, 'start') as mock_start: self.gf.start_listen('event') - self.assertEqual(mock_start.call_count, 1) - self.assertEqual(mock_start.call_args, mock.call()) + assert mock_start.call_count == 1 + assert mock_start.call_args == mock.call() def test_shutdown(self): """Test the shutdown.""" with mock.patch.object(self.gf, '_queue') as mock_queue: self.gf.shutdown('event') - self.assertEqual(mock_queue.put.call_count, 1) - self.assertEqual( - mock_queue.put.call_args, mock.call(self.gf._quit_object) - ) + assert mock_queue.put.call_count == 1 + assert mock_queue.put.call_args == mock.call(self.gf._quit_object) def test_event_listener(self): """Test the event listener.""" with mock.patch.object(self.gf, '_queue') as mock_queue: self.gf.event_listener('foo') - self.assertEqual(mock_queue.put.call_count, 1) - self.assertEqual(mock_queue.put.call_args, mock.call('foo')) + assert mock_queue.put.call_count == 1 + assert mock_queue.put.call_args == mock.call('foo') @patch('time.time') def test_report_attributes(self, mock_time): @@ -135,7 +123,7 @@ class TestGraphite(unittest.TestCase): with mock.patch.object(self.gf, '_send_to_graphite') as mock_send: self.gf._report_attributes('entity', state) actual = mock_send.call_args_list[0][0][0].split('\n') - self.assertEqual(sorted(expected), sorted(actual)) + assert sorted(expected) == sorted(actual) @patch('time.time') def test_report_with_string_state(self, mock_time): @@ -150,7 +138,7 @@ class TestGraphite(unittest.TestCase): with mock.patch.object(self.gf, '_send_to_graphite') as mock_send: self.gf._report_attributes('entity', state) actual = mock_send.call_args_list[0][0][0].split('\n') - self.assertEqual(sorted(expected), sorted(actual)) + assert sorted(expected) == sorted(actual) @patch('time.time') def test_report_with_binary_state(self, mock_time): @@ -162,7 +150,7 @@ class TestGraphite(unittest.TestCase): expected = ['ha.entity.foo 1.000000 12345', 'ha.entity.state 1.000000 12345'] actual = mock_send.call_args_list[0][0][0].split('\n') - self.assertEqual(sorted(expected), sorted(actual)) + assert sorted(expected) == sorted(actual) state.state = STATE_OFF with mock.patch.object(self.gf, '_send_to_graphite') as mock_send: @@ -170,7 +158,7 @@ class TestGraphite(unittest.TestCase): expected = ['ha.entity.foo 1.000000 12345', 'ha.entity.state 0.000000 12345'] actual = mock_send.call_args_list[0][0][0].split('\n') - self.assertEqual(sorted(expected), sorted(actual)) + assert sorted(expected) == sorted(actual) @patch('time.time') def test_send_to_graphite_errors(self, mock_time): @@ -187,32 +175,28 @@ class TestGraphite(unittest.TestCase): def test_send_to_graphite(self, mock_socket): """Test the sending of data.""" self.gf._send_to_graphite('foo') - self.assertEqual(mock_socket.call_count, 1) - self.assertEqual( - mock_socket.call_args, + assert mock_socket.call_count == 1 + assert mock_socket.call_args == \ mock.call(socket.AF_INET, socket.SOCK_STREAM) - ) sock = mock_socket.return_value - self.assertEqual(sock.connect.call_count, 1) - self.assertEqual(sock.connect.call_args, mock.call(('foo', 123))) - self.assertEqual(sock.sendall.call_count, 1) - self.assertEqual( - sock.sendall.call_args, mock.call('foo'.encode('ascii')) - ) - self.assertEqual(sock.send.call_count, 1) - self.assertEqual(sock.send.call_args, mock.call('\n'.encode('ascii'))) - self.assertEqual(sock.close.call_count, 1) - self.assertEqual(sock.close.call_args, mock.call()) + assert sock.connect.call_count == 1 + assert sock.connect.call_args == mock.call(('foo', 123)) + assert sock.sendall.call_count == 1 + assert sock.sendall.call_args == mock.call('foo'.encode('ascii')) + assert sock.send.call_count == 1 + assert sock.send.call_args == mock.call('\n'.encode('ascii')) + assert sock.close.call_count == 1 + assert sock.close.call_args == mock.call() def test_run_stops(self): """Test the stops.""" with mock.patch.object(self.gf, '_queue') as mock_queue: mock_queue.get.return_value = self.gf._quit_object - self.assertEqual(None, self.gf.run()) - self.assertEqual(mock_queue.get.call_count, 1) - self.assertEqual(mock_queue.get.call_args, mock.call()) - self.assertEqual(mock_queue.task_done.call_count, 1) - self.assertEqual(mock_queue.task_done.call_args, mock.call()) + assert self.gf.run() is None + assert mock_queue.get.call_count == 1 + assert mock_queue.get.call_args == mock.call() + assert mock_queue.task_done.call_count == 1 + assert mock_queue.task_done.call_args == mock.call() def test_run(self): """Test the running.""" @@ -236,9 +220,7 @@ class TestGraphite(unittest.TestCase): mock_queue.get.side_effect = fake_get self.gf.run() # Twice for two events, once for the stop - self.assertEqual(3, mock_queue.task_done.call_count) - self.assertEqual(mock_r.call_count, 1) - self.assertEqual( - mock_r.call_args, + assert 3 == mock_queue.task_done.call_count + assert mock_r.call_count == 1 + assert mock_r.call_args == \ mock.call('entity', event.data['new_state']) - ) diff --git a/tests/components/test_history.py b/tests/components/test_history.py index ef2f7a17a..9764af159 100644 --- a/tests/components/test_history.py +++ b/tests/components/test_history.py @@ -47,7 +47,7 @@ class TestComponentHistory(unittest.TestCase): history.CONF_DOMAINS: ['thermostat'], history.CONF_ENTITIES: ['media_player.test']}}}) self.init_recorder() - self.assertTrue(setup_component(self.hass, history.DOMAIN, config)) + assert setup_component(self.hass, history.DOMAIN, config) def test_get_states(self): """Test getting states at a specific point in time.""" @@ -89,9 +89,8 @@ class TestComponentHistory(unittest.TestCase): assert state1 == state2 # Test get_state here because we have a DB setup - self.assertEqual( - states[0], history.get_state(self.hass, future, - states[0].entity_id)) + assert states[0] == \ + history.get_state(self.hass, future, states[0].entity_id) def test_state_changes_during_period(self): """Test state change during period.""" @@ -130,7 +129,7 @@ class TestComponentHistory(unittest.TestCase): hist = history.state_changes_during_period( self.hass, start, end, entity_id) - self.assertEqual(states, hist[entity_id]) + assert states == hist[entity_id] def test_get_last_state_changes(self): """Test number of state changes.""" @@ -163,7 +162,7 @@ class TestComponentHistory(unittest.TestCase): hist = history.get_last_state_changes( self.hass, 2, entity_id) - self.assertEqual(states, hist[entity_id]) + assert states == hist[entity_id] def test_get_significant_states(self): """Test that only significant states are returned. diff --git a/tests/components/test_history_graph.py b/tests/components/test_history_graph.py index 9b7733a7e..80d590939 100644 --- a/tests/components/test_history_graph.py +++ b/tests/components/test_history_graph.py @@ -30,15 +30,15 @@ class TestGraph(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, 'history_graph', config)) - self.assertEqual( - dict(self.hass.states.get('history_graph.name_1').attributes), - { - 'entity_id': ['test.test'], - 'friendly_name': 'name_1', - 'hours_to_show': 24, - 'refresh': 0 - }) + assert setup_component(self.hass, 'history_graph', config) + assert dict( + self.hass.states.get('history_graph.name_1').attributes + ) == { + 'entity_id': ['test.test'], + 'friendly_name': 'name_1', + 'hours_to_show': 24, + 'refresh': 0 + } def init_recorder(self): """Initialize the recorder.""" diff --git a/tests/components/test_influxdb.py b/tests/components/test_influxdb.py index 7d1b75276..5de6e1647 100644 --- a/tests/components/test_influxdb.py +++ b/tests/components/test_influxdb.py @@ -8,7 +8,7 @@ import influxdb as influx_client from homeassistant.setup import setup_component import homeassistant.components.influxdb as influxdb from homeassistant.const import EVENT_STATE_CHANGED, STATE_OFF, STATE_ON, \ - STATE_STANDBY + STATE_STANDBY from tests.common import get_test_home_assistant @@ -45,10 +45,10 @@ class TestInfluxDB(unittest.TestCase): } } assert setup_component(self.hass, influxdb.DOMAIN, config) - self.assertTrue(self.hass.bus.listen.called) - self.assertEqual( - EVENT_STATE_CHANGED, self.hass.bus.listen.call_args_list[0][0][0]) - self.assertTrue(mock_client.return_value.query.called) + assert self.hass.bus.listen.called + assert \ + EVENT_STATE_CHANGED == self.hass.bus.listen.call_args_list[0][0][0] + assert mock_client.return_value.query.called def test_setup_config_defaults(self, mock_client): """Test the setup with default configuration.""" @@ -60,9 +60,9 @@ class TestInfluxDB(unittest.TestCase): } } assert setup_component(self.hass, influxdb.DOMAIN, config) - self.assertTrue(self.hass.bus.listen.called) - self.assertEqual( - EVENT_STATE_CHANGED, self.hass.bus.listen.call_args_list[0][0][0]) + assert self.hass.bus.listen.called + assert \ + EVENT_STATE_CHANGED == self.hass.bus.listen.call_args_list[0][0][0] def test_setup_minimal_config(self, mock_client): """Test the setup with minimal configuration.""" @@ -169,13 +169,9 @@ class TestInfluxDB(unittest.TestCase): self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) mock_client.return_value.write_points.reset_mock() def test_event_listener_no_units(self, mock_client): @@ -204,13 +200,9 @@ class TestInfluxDB(unittest.TestCase): }] self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) mock_client.return_value.write_points.reset_mock() def test_event_listener_inf(self, mock_client): @@ -235,13 +227,9 @@ class TestInfluxDB(unittest.TestCase): }] self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) mock_client.return_value.write_points.reset_mock() def test_event_listener_states(self, mock_client): @@ -267,15 +255,11 @@ class TestInfluxDB(unittest.TestCase): self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() if state_state == 1: - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) else: - self.assertFalse(mock_client.return_value.write_points.called) + assert not mock_client.return_value.write_points.called mock_client.return_value.write_points.reset_mock() def test_event_listener_blacklist(self, mock_client): @@ -301,15 +285,11 @@ class TestInfluxDB(unittest.TestCase): self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() if entity_id == 'ok': - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) else: - self.assertFalse(mock_client.return_value.write_points.called) + assert not mock_client.return_value.write_points.called mock_client.return_value.write_points.reset_mock() def test_event_listener_blacklist_domain(self, mock_client): @@ -336,15 +316,11 @@ class TestInfluxDB(unittest.TestCase): self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() if domain == 'ok': - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) else: - self.assertFalse(mock_client.return_value.write_points.called) + assert not mock_client.return_value.write_points.called mock_client.return_value.write_points.reset_mock() def test_event_listener_whitelist(self, mock_client): @@ -381,15 +357,11 @@ class TestInfluxDB(unittest.TestCase): self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() if entity_id == 'included': - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) else: - self.assertFalse(mock_client.return_value.write_points.called) + assert not mock_client.return_value.write_points.called mock_client.return_value.write_points.reset_mock() def test_event_listener_whitelist_domain(self, mock_client): @@ -427,15 +399,11 @@ class TestInfluxDB(unittest.TestCase): self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() if domain == 'fake': - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) else: - self.assertFalse(mock_client.return_value.write_points.called) + assert not mock_client.return_value.write_points.called mock_client.return_value.write_points.reset_mock() def test_event_listener_invalid_type(self, mock_client): @@ -482,13 +450,9 @@ class TestInfluxDB(unittest.TestCase): self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) mock_client.return_value.write_points.reset_mock() def test_event_listener_default_measurement(self, mock_client): @@ -526,15 +490,11 @@ class TestInfluxDB(unittest.TestCase): self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() if entity_id == 'ok': - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) else: - self.assertFalse(mock_client.return_value.write_points.called) + assert not mock_client.return_value.write_points.called mock_client.return_value.write_points.reset_mock() def test_event_listener_unit_of_measurement_field(self, mock_client): @@ -571,13 +531,9 @@ class TestInfluxDB(unittest.TestCase): }] self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) mock_client.return_value.write_points.reset_mock() def test_event_listener_tags_attributes(self, mock_client): @@ -617,13 +573,9 @@ class TestInfluxDB(unittest.TestCase): }] self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) mock_client.return_value.write_points.reset_mock() def test_event_listener_component_override_measurement(self, mock_client): @@ -678,13 +630,9 @@ class TestInfluxDB(unittest.TestCase): }] self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() - self.assertEqual( - mock_client.return_value.write_points.call_count, 1 - ) - self.assertEqual( - mock_client.return_value.write_points.call_args, + assert mock_client.return_value.write_points.call_count == 1 + assert mock_client.return_value.write_points.call_args == \ mock.call(body) - ) mock_client.return_value.write_points.reset_mock() def test_scheduled_write(self, mock_client): @@ -713,7 +661,7 @@ class TestInfluxDB(unittest.TestCase): self.hass.data[influxdb.DOMAIN].block_till_done() assert mock_sleep.called json_data = mock_client.return_value.write_points.call_args[0][0] - self.assertEqual(mock_client.return_value.write_points.call_count, 2) + assert mock_client.return_value.write_points.call_count == 2 mock_client.return_value.write_points.assert_called_with(json_data) # Write works again @@ -722,7 +670,7 @@ class TestInfluxDB(unittest.TestCase): self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() assert not mock_sleep.called - self.assertEqual(mock_client.return_value.write_points.call_count, 3) + assert mock_client.return_value.write_points.call_count == 3 def test_queue_backlog_full(self, mock_client): """Test the event listener to drop old events.""" @@ -746,8 +694,6 @@ class TestInfluxDB(unittest.TestCase): self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() - self.assertEqual( - mock_client.return_value.write_points.call_count, 0 - ) + assert mock_client.return_value.write_points.call_count == 0 mock_client.return_value.write_points.reset_mock() diff --git a/tests/components/test_init.py b/tests/components/test_init.py index b9152bbdd..768951d46 100644 --- a/tests/components/test_init.py +++ b/tests/components/test_init.py @@ -96,9 +96,9 @@ class TestComponentsCore(unittest.TestCase): def setUp(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() - self.assertTrue(run_coroutine_threadsafe( + assert run_coroutine_threadsafe( comps.async_setup(self.hass, {}), self.hass.loop - ).result()) + ).result() self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Ceiling', STATE_OFF) @@ -110,38 +110,38 @@ class TestComponentsCore(unittest.TestCase): def test_is_on(self): """Test is_on method.""" - self.assertTrue(comps.is_on(self.hass, 'light.Bowl')) - self.assertFalse(comps.is_on(self.hass, 'light.Ceiling')) - self.assertTrue(comps.is_on(self.hass)) - self.assertFalse(comps.is_on(self.hass, 'non_existing.entity')) + assert comps.is_on(self.hass, 'light.Bowl') + assert not comps.is_on(self.hass, 'light.Ceiling') + assert comps.is_on(self.hass) + assert not comps.is_on(self.hass, 'non_existing.entity') def test_turn_on_without_entities(self): """Test turn_on method without entities.""" calls = mock_service(self.hass, 'light', SERVICE_TURN_ON) turn_on(self.hass) self.hass.block_till_done() - self.assertEqual(0, len(calls)) + assert 0 == len(calls) def test_turn_on(self): """Test turn_on method.""" calls = mock_service(self.hass, 'light', SERVICE_TURN_ON) turn_on(self.hass, 'light.Ceiling') self.hass.block_till_done() - self.assertEqual(1, len(calls)) + assert 1 == len(calls) def test_turn_off(self): """Test turn_off method.""" calls = mock_service(self.hass, 'light', SERVICE_TURN_OFF) turn_off(self.hass, 'light.Bowl') self.hass.block_till_done() - self.assertEqual(1, len(calls)) + assert 1 == len(calls) def test_toggle(self): """Test toggle method.""" calls = mock_service(self.hass, 'light', SERVICE_TOGGLE) toggle(self.hass, 'light.Bowl') self.hass.block_till_done() - self.assertEqual(1, len(calls)) + assert 1 == len(calls) @patch('homeassistant.config.os.path.isfile', Mock(return_value=True)) def test_reload_core_conf(self): diff --git a/tests/components/test_input_boolean.py b/tests/components/test_input_boolean.py index b947155e6..9fc9ceaef 100644 --- a/tests/components/test_input_boolean.py +++ b/tests/components/test_input_boolean.py @@ -69,38 +69,34 @@ class TestInputBoolean(unittest.TestCase): ] for cfg in invalid_configs: - self.assertFalse( - setup_component(self.hass, DOMAIN, {DOMAIN: cfg})) + assert not setup_component(self.hass, DOMAIN, {DOMAIN: cfg}) def test_methods(self): """Test is_on, turn_on, turn_off methods.""" - self.assertTrue(setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_1': None, - }})) + }}) entity_id = 'input_boolean.test_1' - self.assertFalse( - is_on(self.hass, entity_id)) + assert not is_on(self.hass, entity_id) turn_on(self.hass, entity_id) self.hass.block_till_done() - self.assertTrue( - is_on(self.hass, entity_id)) + assert is_on(self.hass, entity_id) turn_off(self.hass, entity_id) self.hass.block_till_done() - self.assertFalse( - is_on(self.hass, entity_id)) + assert not is_on(self.hass, entity_id) toggle(self.hass, entity_id) self.hass.block_till_done() - self.assertTrue(is_on(self.hass, entity_id)) + assert is_on(self.hass, entity_id) def test_config_options(self): """Test configuration options.""" @@ -108,33 +104,33 @@ class TestInputBoolean(unittest.TestCase): _LOGGER.debug('ENTITIES @ start: %s', self.hass.states.entity_ids()) - self.assertTrue(setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_1': None, 'test_2': { 'name': 'Hello World', 'icon': 'mdi:work', 'initial': True, }, - }})) + }}) _LOGGER.debug('ENTITIES: %s', self.hass.states.entity_ids()) - self.assertEqual(count_start + 2, len(self.hass.states.entity_ids())) + assert count_start + 2 == len(self.hass.states.entity_ids()) state_1 = self.hass.states.get('input_boolean.test_1') state_2 = self.hass.states.get('input_boolean.test_2') - self.assertIsNotNone(state_1) - self.assertIsNotNone(state_2) + assert state_1 is not None + assert state_2 is not None - self.assertEqual(STATE_OFF, state_1.state) - self.assertNotIn(ATTR_ICON, state_1.attributes) - self.assertNotIn(ATTR_FRIENDLY_NAME, state_1.attributes) + assert STATE_OFF == state_1.state + assert ATTR_ICON not in state_1.attributes + assert ATTR_FRIENDLY_NAME not in state_1.attributes - self.assertEqual(STATE_ON, state_2.state) - self.assertEqual('Hello World', - state_2.attributes.get(ATTR_FRIENDLY_NAME)) - self.assertEqual('mdi:work', state_2.attributes.get(ATTR_ICON)) + assert STATE_ON == state_2.state + assert 'Hello World' == \ + state_2.attributes.get(ATTR_FRIENDLY_NAME) + assert 'mdi:work' == state_2.attributes.get(ATTR_ICON) @asyncio.coroutine diff --git a/tests/components/test_input_datetime.py b/tests/components/test_input_datetime.py index 9ced2aaa0..e7f6b50c4 100644 --- a/tests/components/test_input_datetime.py +++ b/tests/components/test_input_datetime.py @@ -46,8 +46,7 @@ class TestInputDatetime(unittest.TestCase): }}, ] for cfg in invalid_configs: - self.assertFalse( - setup_component(self.hass, DOMAIN, {DOMAIN: cfg})) + assert not setup_component(self.hass, DOMAIN, {DOMAIN: cfg}) @asyncio.coroutine diff --git a/tests/components/test_input_number.py b/tests/components/test_input_number.py index a53704e1d..3129b4445 100644 --- a/tests/components/test_input_number.py +++ b/tests/components/test_input_number.py @@ -73,97 +73,95 @@ class TestInputNumber(unittest.TestCase): }}, ] for cfg in invalid_configs: - self.assertFalse( - setup_component(self.hass, DOMAIN, {DOMAIN: cfg})) + assert not setup_component(self.hass, DOMAIN, {DOMAIN: cfg}) def test_set_value(self): """Test set_value method.""" - self.assertTrue(setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_1': { 'initial': 50, 'min': 0, 'max': 100, }, - }})) + }}) entity_id = 'input_number.test_1' state = self.hass.states.get(entity_id) - self.assertEqual(50, float(state.state)) + assert 50 == float(state.state) set_value(self.hass, entity_id, '30.4') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(30.4, float(state.state)) + assert 30.4 == float(state.state) set_value(self.hass, entity_id, '70') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(70, float(state.state)) + assert 70 == float(state.state) set_value(self.hass, entity_id, '110') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(70, float(state.state)) + assert 70 == float(state.state) def test_increment(self): """Test increment method.""" - self.assertTrue(setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_2': { 'initial': 50, 'min': 0, 'max': 51, }, - }})) + }}) entity_id = 'input_number.test_2' state = self.hass.states.get(entity_id) - self.assertEqual(50, float(state.state)) + assert 50 == float(state.state) increment(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(51, float(state.state)) + assert 51 == float(state.state) increment(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(51, float(state.state)) + assert 51 == float(state.state) def test_decrement(self): """Test decrement method.""" - self.assertTrue(setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_3': { 'initial': 50, 'min': 49, 'max': 100, }, - }})) + }}) entity_id = 'input_number.test_3' state = self.hass.states.get(entity_id) - self.assertEqual(50, float(state.state)) + assert 50 == float(state.state) decrement(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(49, float(state.state)) + assert 49 == float(state.state) decrement(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual(49, float(state.state)) + assert 49 == float(state.state) def test_mode(self): """Test mode settings.""" - self.assertTrue( - setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_default_slider': { 'min': 0, 'max': 100, @@ -178,19 +176,19 @@ class TestInputNumber(unittest.TestCase): 'max': 100, 'mode': 'slider', }, - }})) + }}) state = self.hass.states.get('input_number.test_default_slider') assert state - self.assertEqual('slider', state.attributes['mode']) + assert 'slider' == state.attributes['mode'] state = self.hass.states.get('input_number.test_explicit_box') assert state - self.assertEqual('box', state.attributes['mode']) + assert 'box' == state.attributes['mode'] state = self.hass.states.get('input_number.test_explicit_slider') assert state - self.assertEqual('slider', state.attributes['mode']) + assert 'slider' == state.attributes['mode'] @asyncio.coroutine diff --git a/tests/components/test_input_select.py b/tests/components/test_input_select.py index 25f6d1c76..684c526cb 100644 --- a/tests/components/test_input_select.py +++ b/tests/components/test_input_select.py @@ -76,41 +76,38 @@ class TestInputSelect(unittest.TestCase): ] for cfg in invalid_configs: - self.assertFalse( - setup_component(self.hass, DOMAIN, {DOMAIN: cfg})) + assert not setup_component(self.hass, DOMAIN, {DOMAIN: cfg}) def test_select_option(self): """Test select_option methods.""" - self.assertTrue( - setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_1': { 'options': [ 'some option', 'another option', ], }, - }})) + }}) entity_id = 'input_select.test_1' state = self.hass.states.get(entity_id) - self.assertEqual('some option', state.state) + assert 'some option' == state.state select_option(self.hass, entity_id, 'another option') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual('another option', state.state) + assert 'another option' == state.state select_option(self.hass, entity_id, 'non existing option') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual('another option', state.state) + assert 'another option' == state.state def test_select_next(self): """Test select_next methods.""" - self.assertTrue( - setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_1': { 'options': [ 'first option', @@ -119,28 +116,27 @@ class TestInputSelect(unittest.TestCase): ], 'initial': 'middle option', }, - }})) + }}) entity_id = 'input_select.test_1' state = self.hass.states.get(entity_id) - self.assertEqual('middle option', state.state) + assert 'middle option' == state.state select_next(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual('last option', state.state) + assert 'last option' == state.state select_next(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual('first option', state.state) + assert 'first option' == state.state def test_select_previous(self): """Test select_previous methods.""" - self.assertTrue( - setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_1': { 'options': [ 'first option', @@ -149,23 +145,23 @@ class TestInputSelect(unittest.TestCase): ], 'initial': 'middle option', }, - }})) + }}) entity_id = 'input_select.test_1' state = self.hass.states.get(entity_id) - self.assertEqual('middle option', state.state) + assert 'middle option' == state.state select_previous(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual('first option', state.state) + assert 'first option' == state.state select_previous(self.hass, entity_id) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual('last option', state.state) + assert 'last option' == state.state def test_config_options(self): """Test configuration options.""" @@ -177,7 +173,7 @@ class TestInputSelect(unittest.TestCase): 'Best Option', ] - self.assertTrue(setup_component(self.hass, DOMAIN, { + assert setup_component(self.hass, DOMAIN, { DOMAIN: { 'test_1': { 'options': [ @@ -192,32 +188,31 @@ class TestInputSelect(unittest.TestCase): 'initial': 'Better Option', }, } - })) + }) - self.assertEqual(count_start + 2, len(self.hass.states.entity_ids())) + assert count_start + 2 == len(self.hass.states.entity_ids()) state_1 = self.hass.states.get('input_select.test_1') state_2 = self.hass.states.get('input_select.test_2') - self.assertIsNotNone(state_1) - self.assertIsNotNone(state_2) + assert state_1 is not None + assert state_2 is not None - self.assertEqual('1', state_1.state) - self.assertEqual(['1', '2'], - state_1.attributes.get(ATTR_OPTIONS)) - self.assertNotIn(ATTR_ICON, state_1.attributes) + assert '1' == state_1.state + assert ['1', '2'] == \ + state_1.attributes.get(ATTR_OPTIONS) + assert ATTR_ICON not in state_1.attributes - self.assertEqual('Better Option', state_2.state) - self.assertEqual(test_2_options, - state_2.attributes.get(ATTR_OPTIONS)) - self.assertEqual('Hello World', - state_2.attributes.get(ATTR_FRIENDLY_NAME)) - self.assertEqual('mdi:work', state_2.attributes.get(ATTR_ICON)) + assert 'Better Option' == state_2.state + assert test_2_options == \ + state_2.attributes.get(ATTR_OPTIONS) + assert 'Hello World' == \ + state_2.attributes.get(ATTR_FRIENDLY_NAME) + assert 'mdi:work' == state_2.attributes.get(ATTR_ICON) def test_set_options_service(self): """Test set_options service.""" - self.assertTrue( - setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_1': { 'options': [ 'first option', @@ -226,28 +221,28 @@ class TestInputSelect(unittest.TestCase): ], 'initial': 'middle option', }, - }})) + }}) entity_id = 'input_select.test_1' state = self.hass.states.get(entity_id) - self.assertEqual('middle option', state.state) + assert 'middle option' == state.state data = {ATTR_OPTIONS: ["test1", "test2"], "entity_id": entity_id} self.hass.services.call(DOMAIN, SERVICE_SET_OPTIONS, data) self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual('test1', state.state) + assert 'test1' == state.state select_option(self.hass, entity_id, 'first option') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual('test1', state.state) + assert 'test1' == state.state select_option(self.hass, entity_id, 'test2') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual('test2', state.state) + assert 'test2' == state.state @asyncio.coroutine diff --git a/tests/components/test_input_text.py b/tests/components/test_input_text.py index bea145390..110a3190b 100644 --- a/tests/components/test_input_text.py +++ b/tests/components/test_input_text.py @@ -50,39 +50,37 @@ class TestInputText(unittest.TestCase): }}, ] for cfg in invalid_configs: - self.assertFalse( - setup_component(self.hass, DOMAIN, {DOMAIN: cfg})) + assert not setup_component(self.hass, DOMAIN, {DOMAIN: cfg}) def test_set_value(self): """Test set_value method.""" - self.assertTrue(setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_1': { 'initial': 'test', 'min': 3, 'max': 10, }, - }})) + }}) entity_id = 'input_text.test_1' state = self.hass.states.get(entity_id) - self.assertEqual('test', str(state.state)) + assert 'test' == str(state.state) set_value(self.hass, entity_id, 'testing') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual('testing', str(state.state)) + assert 'testing' == str(state.state) set_value(self.hass, entity_id, 'testing too long') self.hass.block_till_done() state = self.hass.states.get(entity_id) - self.assertEqual('testing', str(state.state)) + assert 'testing' == str(state.state) def test_mode(self): """Test mode settings.""" - self.assertTrue( - setup_component(self.hass, DOMAIN, {DOMAIN: { + assert setup_component(self.hass, DOMAIN, {DOMAIN: { 'test_default_text': { 'initial': 'test', 'min': 3, @@ -100,19 +98,19 @@ class TestInputText(unittest.TestCase): 'max': 10, 'mode': 'password', }, - }})) + }}) state = self.hass.states.get('input_text.test_default_text') assert state - self.assertEqual('text', state.attributes['mode']) + assert 'text' == state.attributes['mode'] state = self.hass.states.get('input_text.test_explicit_text') assert state - self.assertEqual('text', state.attributes['mode']) + assert 'text' == state.attributes['mode'] state = self.hass.states.get('input_text.test_explicit_password') assert state - self.assertEqual('password', state.attributes['mode']) + assert 'password' == state.attributes['mode'] @asyncio.coroutine diff --git a/tests/components/test_introduction.py b/tests/components/test_introduction.py index b7099d048..c414ab97a 100644 --- a/tests/components/test_introduction.py +++ b/tests/components/test_introduction.py @@ -20,4 +20,4 @@ class TestIntroduction(unittest.TestCase): def test_setup(self): """Test introduction setup.""" - self.assertTrue(setup_component(self.hass, introduction.DOMAIN, {})) + assert setup_component(self.hass, introduction.DOMAIN, {}) diff --git a/tests/components/test_logbook.py b/tests/components/test_logbook.py index 1100a16b3..89528c177 100644 --- a/tests/components/test_logbook.py +++ b/tests/components/test_logbook.py @@ -63,15 +63,15 @@ class TestComponentLogbook(unittest.TestCase): # scheduled. This means that they may not have been processed yet. self.hass.block_till_done() - self.assertEqual(1, len(calls)) + assert 1 == len(calls) last_call = calls[-1] - self.assertEqual('Alarm', last_call.data.get(logbook.ATTR_NAME)) - self.assertEqual('is triggered', last_call.data.get( - logbook.ATTR_MESSAGE)) - self.assertEqual('switch', last_call.data.get(logbook.ATTR_DOMAIN)) - self.assertEqual('switch.test_switch', last_call.data.get( - logbook.ATTR_ENTITY_ID)) + assert 'Alarm' == last_call.data.get(logbook.ATTR_NAME) + assert 'is triggered' == last_call.data.get( + logbook.ATTR_MESSAGE) + assert 'switch' == last_call.data.get(logbook.ATTR_DOMAIN) + assert 'switch.test_switch' == last_call.data.get( + logbook.ATTR_ENTITY_ID) def test_service_call_create_log_book_entry_no_message(self): """Test if service call create log book entry without message.""" @@ -90,7 +90,7 @@ class TestComponentLogbook(unittest.TestCase): # scheduled. This means that they may not have been processed yet. self.hass.block_till_done() - self.assertEqual(0, len(calls)) + assert 0 == len(calls) def test_humanify_filter_sensor(self): """Test humanify filter too frequent sensor values.""" @@ -106,7 +106,7 @@ class TestComponentLogbook(unittest.TestCase): entries = list(logbook.humanify(self.hass, (eventA, eventB, eventC))) - self.assertEqual(2, len(entries)) + assert 2 == len(entries) self.assert_entry( entries[0], pointB, 'bla', domain='sensor', entity_id=entity_id) @@ -123,7 +123,7 @@ class TestComponentLogbook(unittest.TestCase): entries = list(logbook.humanify(self.hass, (eventA,))) - self.assertEqual(0, len(entries)) + assert 0 == len(entries) def test_exclude_new_entities(self): """Test if events are excluded on first update.""" @@ -140,7 +140,7 @@ class TestComponentLogbook(unittest.TestCase): eventA, eventB), {}) entries = list(logbook.humanify(self.hass, events)) - self.assertEqual(2, len(entries)) + assert 2 == len(entries) self.assert_entry( entries[0], name='Home Assistant', message='stopped', domain=ha.DOMAIN) @@ -162,7 +162,7 @@ class TestComponentLogbook(unittest.TestCase): eventA, eventB), {}) entries = list(logbook.humanify(self.hass, events)) - self.assertEqual(2, len(entries)) + assert 2 == len(entries) self.assert_entry( entries[0], name='Home Assistant', message='stopped', domain=ha.DOMAIN) @@ -184,7 +184,7 @@ class TestComponentLogbook(unittest.TestCase): eventA, eventB), {}) entries = list(logbook.humanify(self.hass, events)) - self.assertEqual(2, len(entries)) + assert 2 == len(entries) self.assert_entry( entries[0], name='Home Assistant', message='stopped', domain=ha.DOMAIN) @@ -210,7 +210,7 @@ class TestComponentLogbook(unittest.TestCase): config[logbook.DOMAIN]) entries = list(logbook.humanify(self.hass, events)) - self.assertEqual(2, len(entries)) + assert 2 == len(entries) self.assert_entry( entries[0], name='Home Assistant', message='stopped', domain=ha.DOMAIN) @@ -236,7 +236,7 @@ class TestComponentLogbook(unittest.TestCase): config[logbook.DOMAIN]) entries = list(logbook.humanify(self.hass, events)) - self.assertEqual(2, len(entries)) + assert 2 == len(entries) self.assert_entry(entries[0], name='Home Assistant', message='started', domain=ha.DOMAIN) self.assert_entry(entries[1], pointB, 'blu', domain='sensor', @@ -273,7 +273,7 @@ class TestComponentLogbook(unittest.TestCase): config[logbook.DOMAIN]) entries = list(logbook.humanify(self.hass, events)) - self.assertEqual(2, len(entries)) + assert 2 == len(entries) self.assert_entry( entries[0], name='Home Assistant', message='stopped', domain=ha.DOMAIN) @@ -299,7 +299,7 @@ class TestComponentLogbook(unittest.TestCase): config[logbook.DOMAIN]) entries = list(logbook.humanify(self.hass, events)) - self.assertEqual(2, len(entries)) + assert 2 == len(entries) self.assert_entry( entries[0], name='Home Assistant', message='stopped', domain=ha.DOMAIN) @@ -325,7 +325,7 @@ class TestComponentLogbook(unittest.TestCase): config[logbook.DOMAIN]) entries = list(logbook.humanify(self.hass, events)) - self.assertEqual(2, len(entries)) + assert 2 == len(entries) self.assert_entry(entries[0], name='Home Assistant', message='started', domain=ha.DOMAIN) self.assert_entry(entries[1], pointB, 'blu', domain='sensor', @@ -359,7 +359,7 @@ class TestComponentLogbook(unittest.TestCase): eventB1, eventB2), config[logbook.DOMAIN]) entries = list(logbook.humanify(self.hass, events)) - self.assertEqual(3, len(entries)) + assert 3 == len(entries) self.assert_entry(entries[0], name='Home Assistant', message='started', domain=ha.DOMAIN) self.assert_entry(entries[1], pointA, 'blu', domain='sensor', @@ -380,7 +380,7 @@ class TestComponentLogbook(unittest.TestCase): events = logbook._exclude_events((eventA, eventB), {}) entries = list(logbook.humanify(self.hass, events)) - self.assertEqual(1, len(entries)) + assert 1 == len(entries) self.assert_entry(entries[0], pointA, 'bla', domain='switch', entity_id=entity_id) @@ -398,7 +398,7 @@ class TestComponentLogbook(unittest.TestCase): events = logbook._exclude_events((eventA, eventB), {}) entries = list(logbook.humanify(self.hass, events)) - self.assertEqual(1, len(entries)) + assert 1 == len(entries) self.assert_entry(entries[0], pointA, 'bla', domain='switch', entity_id=entity_id) @@ -412,7 +412,7 @@ class TestComponentLogbook(unittest.TestCase): ha.Event(EVENT_HOMEASSISTANT_START), ))) - self.assertEqual(1, len(entries)) + assert 1 == len(entries) self.assert_entry( entries[0], name='Home Assistant', message='restarted', domain=ha.DOMAIN) @@ -427,7 +427,7 @@ class TestComponentLogbook(unittest.TestCase): self.create_state_changed_event(pointA, entity_id, 10) ))) - self.assertEqual(2, len(entries)) + assert 2 == len(entries) self.assert_entry( entries[0], name='Home Assistant', message='started', domain=ha.DOMAIN) @@ -445,21 +445,21 @@ class TestComponentLogbook(unittest.TestCase): eventA = self.create_state_changed_event(pointA, 'switch.bla', 10) to_state = ha.State.from_dict(eventA.data.get('new_state')) message = logbook._entry_message_from_state(to_state.domain, to_state) - self.assertEqual('changed to 10', message) + assert 'changed to 10' == message # message for a switch turned on eventA = self.create_state_changed_event(pointA, 'switch.bla', STATE_ON) to_state = ha.State.from_dict(eventA.data.get('new_state')) message = logbook._entry_message_from_state(to_state.domain, to_state) - self.assertEqual('turned on', message) + assert 'turned on' == message # message for a switch turned off eventA = self.create_state_changed_event(pointA, 'switch.bla', STATE_OFF) to_state = ha.State.from_dict(eventA.data.get('new_state')) message = logbook._entry_message_from_state(to_state.domain, to_state) - self.assertEqual('turned off', message) + assert 'turned off' == message def test_entry_message_from_state_device_tracker(self): """Test if logbook message is correctly created for device tracker.""" @@ -470,14 +470,14 @@ class TestComponentLogbook(unittest.TestCase): STATE_NOT_HOME) to_state = ha.State.from_dict(eventA.data.get('new_state')) message = logbook._entry_message_from_state(to_state.domain, to_state) - self.assertEqual('is away', message) + assert 'is away' == message # message for a device tracker "home" state eventA = self.create_state_changed_event(pointA, 'device_tracker.john', 'work') to_state = ha.State.from_dict(eventA.data.get('new_state')) message = logbook._entry_message_from_state(to_state.domain, to_state) - self.assertEqual('is at work', message) + assert 'is at work' == message def test_entry_message_from_state_sun(self): """Test if logbook message is correctly created for sun.""" @@ -488,14 +488,14 @@ class TestComponentLogbook(unittest.TestCase): sun.STATE_ABOVE_HORIZON) to_state = ha.State.from_dict(eventA.data.get('new_state')) message = logbook._entry_message_from_state(to_state.domain, to_state) - self.assertEqual('has risen', message) + assert 'has risen' == message # message for a sun set eventA = self.create_state_changed_event(pointA, 'sun.sun', sun.STATE_BELOW_HORIZON) to_state = ha.State.from_dict(eventA.data.get('new_state')) message = logbook._entry_message_from_state(to_state.domain, to_state) - self.assertEqual('has set', message) + assert 'has set' == message def test_process_custom_logbook_entries(self): """Test if custom log book entries get added as an entry.""" @@ -511,7 +511,7 @@ class TestComponentLogbook(unittest.TestCase): }), ))) - self.assertEqual(1, len(entries)) + assert 1 == len(entries) self.assert_entry( entries[0], name=name, message=message, domain='sun', entity_id=entity_id) @@ -520,19 +520,19 @@ class TestComponentLogbook(unittest.TestCase): domain=None, entity_id=None): """Assert an entry is what is expected.""" if when: - self.assertEqual(when, entry['when']) + assert when == entry['when'] if name: - self.assertEqual(name, entry['name']) + assert name == entry['name'] if message: - self.assertEqual(message, entry['message']) + assert message == entry['message'] if domain: - self.assertEqual(domain, entry['domain']) + assert domain == entry['domain'] if entity_id: - self.assertEqual(entity_id, entry['entity_id']) + assert entity_id == entry['entity_id'] def create_state_changed_event(self, event_time_fired, entity_id, state, attributes=None, last_changed=None, diff --git a/tests/components/test_logentries.py b/tests/components/test_logentries.py index 843a043ce..2de6be0fd 100644 --- a/tests/components/test_logentries.py +++ b/tests/components/test_logentries.py @@ -29,10 +29,10 @@ class TestLogentries(unittest.TestCase): } } self.hass.bus.listen = mock.MagicMock() - self.assertTrue(setup_component(self.hass, logentries.DOMAIN, config)) - self.assertTrue(self.hass.bus.listen.called) - self.assertEqual(EVENT_STATE_CHANGED, - self.hass.bus.listen.call_args_list[0][0][0]) + assert setup_component(self.hass, logentries.DOMAIN, config) + assert self.hass.bus.listen.called + assert EVENT_STATE_CHANGED == \ + self.hass.bus.listen.call_args_list[0][0][0] def test_setup_config_defaults(self): """Test setup with defaults.""" @@ -42,10 +42,10 @@ class TestLogentries(unittest.TestCase): } } self.hass.bus.listen = mock.MagicMock() - self.assertTrue(setup_component(self.hass, logentries.DOMAIN, config)) - self.assertTrue(self.hass.bus.listen.called) - self.assertEqual(EVENT_STATE_CHANGED, - self.hass.bus.listen.call_args_list[0][0][0]) + assert setup_component(self.hass, logentries.DOMAIN, config) + assert self.hass.bus.listen.called + assert EVENT_STATE_CHANGED == \ + self.hass.bus.listen.call_args_list[0][0][0] def _setup(self, mock_requests): """Test the setup.""" @@ -91,9 +91,7 @@ class TestLogentries(unittest.TestCase): 'logs/token', 'event': body} self.handler_method(event) - self.assertEqual(self.mock_post.call_count, 1) - self.assertEqual( - self.mock_post.call_args, + assert self.mock_post.call_count == 1 + assert self.mock_post.call_args == \ mock.call(payload['host'], data=payload, timeout=10) - ) self.mock_post.reset_mock() diff --git a/tests/components/test_logger.py b/tests/components/test_logger.py index f774af216..cb65d5b3f 100644 --- a/tests/components/test_logger.py +++ b/tests/components/test_logger.py @@ -40,24 +40,24 @@ class TestUpdater(unittest.TestCase): def assert_logged(self, name, level): """Assert that a certain record was logged.""" - self.assertTrue(self.log_filter.filter(RECORD(name, level))) + assert self.log_filter.filter(RECORD(name, level)) def assert_not_logged(self, name, level): """Assert that a certain record was not logged.""" - self.assertFalse(self.log_filter.filter(RECORD(name, level))) + assert not self.log_filter.filter(RECORD(name, level)) def test_logger_setup(self): """Use logger to create a logging filter.""" self.setup_logger(TEST_CONFIG) - self.assertTrue(len(logging.root.handlers) > 0) + assert len(logging.root.handlers) > 0 handler = logging.root.handlers[-1] - self.assertEqual(len(handler.filters), 1) + assert len(handler.filters) == 1 log_filter = handler.filters[0].logfilter - self.assertEqual(log_filter['default'], logging.WARNING) - self.assertEqual(log_filter['logs']['test'], logging.INFO) + assert log_filter['default'] == logging.WARNING + assert log_filter['logs']['test'] == logging.INFO def test_logger_test_filters(self): """Test resulting filter operation.""" diff --git a/tests/components/test_melissa.py b/tests/components/test_melissa.py index e39ceb1ad..020d4f7db 100644 --- a/tests/components/test_melissa.py +++ b/tests/components/test_melissa.py @@ -31,8 +31,6 @@ class TestMelissa(unittest.TestCase): mocked_melissa.Melissa.assert_called_with( username="********", password="********") - self.assertIn(melissa.DATA_MELISSA, self.hass.data) - self.assertIsInstance( - self.hass.data[melissa.DATA_MELISSA], type( - mocked_melissa.Melissa()) - ) + assert melissa.DATA_MELISSA in self.hass.data + assert isinstance(self.hass.data[melissa.DATA_MELISSA], type( + mocked_melissa.Melissa())) diff --git a/tests/components/test_nuheat.py b/tests/components/test_nuheat.py index 2b0f249f4..eec93f531 100644 --- a/tests/components/test_nuheat.py +++ b/tests/components/test_nuheat.py @@ -34,12 +34,11 @@ class TestNuHeat(unittest.TestCase): nuheat.setup(self.hass, self.config) mocked_nuheat.NuHeat.assert_called_with("warm", "feet") - self.assertIn(nuheat.DOMAIN, self.hass.data) - self.assertEqual(2, len(self.hass.data[nuheat.DOMAIN])) - self.assertIsInstance( - self.hass.data[nuheat.DOMAIN][0], type(mocked_nuheat.NuHeat()) - ) - self.assertEqual(self.hass.data[nuheat.DOMAIN][1], "thermostat123") + assert nuheat.DOMAIN in self.hass.data + assert 2 == len(self.hass.data[nuheat.DOMAIN]) + assert isinstance(self.hass.data[nuheat.DOMAIN][0], + type(mocked_nuheat.NuHeat())) + assert self.hass.data[nuheat.DOMAIN][1] == "thermostat123" mocked_load.assert_called_with( self.hass, "climate", nuheat.DOMAIN, {}, self.config diff --git a/tests/components/test_pilight.py b/tests/components/test_pilight.py index e630a354f..01582b364 100644 --- a/tests/components/test_pilight.py +++ b/tests/components/test_pilight.py @@ -85,11 +85,11 @@ class TestPilight(unittest.TestCase): with assert_setup_component(4): with patch('pilight.pilight.Client', side_effect=socket.error) as mock_client: - self.assertFalse(setup_component( - self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}})) + assert not setup_component( + self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) mock_client.assert_called_once_with(host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT) - self.assertEqual(1, mock_error.call_count) + assert 1 == mock_error.call_count @patch('homeassistant.components.pilight._LOGGER.error') def test_connection_timeout_error(self, mock_error): @@ -97,11 +97,11 @@ class TestPilight(unittest.TestCase): with assert_setup_component(4): with patch('pilight.pilight.Client', side_effect=socket.timeout) as mock_client: - self.assertFalse(setup_component( - self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}})) + assert not setup_component( + self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) mock_client.assert_called_once_with(host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT) - self.assertEqual(1, mock_error.call_count) + assert 1 == mock_error.call_count @patch('pilight.pilight.Client', PilightDaemonSim) @patch('homeassistant.core._LOGGER.error') @@ -109,8 +109,8 @@ class TestPilight(unittest.TestCase): def test_send_code_no_protocol(self, mock_pilight_error, mock_error): """Try to send data without protocol information, should give error.""" with assert_setup_component(4): - self.assertTrue(setup_component( - self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}})) + assert setup_component( + self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) # Call without protocol info, should be ignored with error self.hass.services.call(pilight.DOMAIN, pilight.SERVICE_NAME, @@ -119,17 +119,16 @@ class TestPilight(unittest.TestCase): blocking=True) self.hass.block_till_done() error_log_call = mock_error.call_args_list[-1] - self.assertTrue( - 'required key not provided @ data[\'protocol\']' in - str(error_log_call)) + assert 'required key not provided @ data[\'protocol\']' in \ + str(error_log_call) @patch('pilight.pilight.Client', PilightDaemonSim) @patch('tests.components.test_pilight._LOGGER.error') def test_send_code(self, mock_pilight_error): """Try to send proper data.""" with assert_setup_component(4): - self.assertTrue(setup_component( - self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}})) + assert setup_component( + self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) # Call with protocol info, should not give error service_data = {'protocol': 'test', @@ -140,7 +139,7 @@ class TestPilight(unittest.TestCase): self.hass.block_till_done() error_log_call = mock_pilight_error.call_args_list[-1] service_data['protocol'] = [service_data['protocol']] - self.assertTrue(str(service_data) in str(error_log_call)) + assert str(service_data) in str(error_log_call) @patch('pilight.pilight.Client', PilightDaemonSim) @patch('homeassistant.components.pilight._LOGGER.error') @@ -149,8 +148,8 @@ class TestPilight(unittest.TestCase): with assert_setup_component(4): with patch('pilight.pilight.Client.send_code', side_effect=IOError): - self.assertTrue(setup_component( - self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}})) + assert setup_component( + self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) # Call with protocol info, should not give error service_data = {'protocol': 'test', @@ -160,16 +159,16 @@ class TestPilight(unittest.TestCase): blocking=True) self.hass.block_till_done() error_log_call = mock_pilight_error.call_args_list[-1] - self.assertTrue('Pilight send failed' in str(error_log_call)) + assert 'Pilight send failed' in str(error_log_call) @patch('pilight.pilight.Client', PilightDaemonSim) @patch('tests.components.test_pilight._LOGGER.error') def test_send_code_delay(self, mock_pilight_error): """Try to send proper data with delay afterwards.""" with assert_setup_component(4): - self.assertTrue(setup_component( + assert setup_component( self.hass, pilight.DOMAIN, - {pilight.DOMAIN: {pilight.CONF_SEND_DELAY: 5.0}})) + {pilight.DOMAIN: {pilight.CONF_SEND_DELAY: 5.0}}) # Call with protocol info, should not give error service_data1 = {'protocol': 'test11', @@ -189,47 +188,44 @@ class TestPilight(unittest.TestCase): {ha.ATTR_NOW: dt_util.utcnow()}) self.hass.block_till_done() error_log_call = mock_pilight_error.call_args_list[-1] - self.assertTrue(str(service_data1) in str(error_log_call)) + assert str(service_data1) in str(error_log_call) new_time = dt_util.utcnow() + timedelta(seconds=5) self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: new_time}) self.hass.block_till_done() error_log_call = mock_pilight_error.call_args_list[-1] - self.assertTrue(str(service_data2) in str(error_log_call)) + assert str(service_data2) in str(error_log_call) @patch('pilight.pilight.Client', PilightDaemonSim) @patch('tests.components.test_pilight._LOGGER.error') def test_start_stop(self, mock_pilight_error): """Check correct startup and stop of pilight daemon.""" with assert_setup_component(4): - self.assertTrue(setup_component( - self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}})) + assert setup_component( + self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) # Test startup self.hass.start() self.hass.block_till_done() error_log_call = mock_pilight_error.call_args_list[-2] - self.assertTrue( - 'PilightDaemonSim callback' in str(error_log_call)) + assert 'PilightDaemonSim callback' in str(error_log_call) error_log_call = mock_pilight_error.call_args_list[-1] - self.assertTrue( - 'PilightDaemonSim start' in str(error_log_call)) + assert 'PilightDaemonSim start' in str(error_log_call) # Test stop self.skip_teardown_stop = True self.hass.stop() error_log_call = mock_pilight_error.call_args_list[-1] - self.assertTrue( - 'PilightDaemonSim stop' in str(error_log_call)) + assert 'PilightDaemonSim stop' in str(error_log_call) @patch('pilight.pilight.Client', PilightDaemonSim) @patch('homeassistant.core._LOGGER.info') def test_receive_code(self, mock_info): """Check if code receiving via pilight daemon works.""" with assert_setup_component(4): - self.assertTrue(setup_component( - self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}})) + assert setup_component( + self.hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) # Test startup self.hass.start() @@ -243,8 +239,8 @@ class TestPilight(unittest.TestCase): # Check if all message parts are put on event bus for key, value in expected_message.items(): - self.assertTrue(str(key) in str(error_log_call)) - self.assertTrue(str(value) in str(error_log_call)) + assert str(key) in str(error_log_call) + assert str(value) in str(error_log_call) @patch('pilight.pilight.Client', PilightDaemonSim) @patch('homeassistant.core._LOGGER.info') @@ -256,9 +252,9 @@ class TestPilight(unittest.TestCase): 'uuid': [PilightDaemonSim.test_message['uuid']], 'id': [PilightDaemonSim.test_message['message']['id']], 'unit': [PilightDaemonSim.test_message['message']['unit']]} - self.assertTrue(setup_component( + assert setup_component( self.hass, pilight.DOMAIN, - {pilight.DOMAIN: {"whitelist": whitelist}})) + {pilight.DOMAIN: {"whitelist": whitelist}}) self.hass.start() self.hass.block_till_done() @@ -271,8 +267,8 @@ class TestPilight(unittest.TestCase): # Check if all message parts are put on event bus for key, value in expected_message.items(): - self.assertTrue(str(key) in str(info_log_call)) - self.assertTrue(str(value) in str(info_log_call)) + assert str(key) in str(info_log_call) + assert str(value) in str(info_log_call) @patch('pilight.pilight.Client', PilightDaemonSim) @patch('homeassistant.core._LOGGER.info') @@ -282,9 +278,9 @@ class TestPilight(unittest.TestCase): whitelist = { 'protocol': [PilightDaemonSim.test_message['protocol']], 'id': [PilightDaemonSim.test_message['message']['id']]} - self.assertTrue(setup_component( + assert setup_component( self.hass, pilight.DOMAIN, - {pilight.DOMAIN: {"whitelist": whitelist}})) + {pilight.DOMAIN: {"whitelist": whitelist}}) self.hass.start() self.hass.block_till_done() @@ -297,8 +293,8 @@ class TestPilight(unittest.TestCase): # Check if all message parts are put on event bus for key, value in expected_message.items(): - self.assertTrue(str(key) in str(info_log_call)) - self.assertTrue(str(value) in str(info_log_call)) + assert str(key) in str(info_log_call) + assert str(value) in str(info_log_call) @patch('pilight.pilight.Client', PilightDaemonSim) @patch('homeassistant.core._LOGGER.info') @@ -309,9 +305,9 @@ class TestPilight(unittest.TestCase): 'protocol': [PilightDaemonSim.test_message['protocol'], 'other_protocol'], 'id': [PilightDaemonSim.test_message['message']['id']]} - self.assertTrue(setup_component( + assert setup_component( self.hass, pilight.DOMAIN, - {pilight.DOMAIN: {"whitelist": whitelist}})) + {pilight.DOMAIN: {"whitelist": whitelist}}) self.hass.start() self.hass.block_till_done() @@ -324,8 +320,8 @@ class TestPilight(unittest.TestCase): # Check if all message parts are put on event bus for key, value in expected_message.items(): - self.assertTrue(str(key) in str(info_log_call)) - self.assertTrue(str(value) in str(info_log_call)) + assert str(key) in str(info_log_call) + assert str(value) in str(info_log_call) @patch('pilight.pilight.Client', PilightDaemonSim) @patch('homeassistant.core._LOGGER.info') @@ -335,16 +331,16 @@ class TestPilight(unittest.TestCase): whitelist = { 'protocol': ['wrong_protocol'], 'id': [PilightDaemonSim.test_message['message']['id']]} - self.assertTrue(setup_component( + assert setup_component( self.hass, pilight.DOMAIN, - {pilight.DOMAIN: {"whitelist": whitelist}})) + {pilight.DOMAIN: {"whitelist": whitelist}}) self.hass.start() self.hass.block_till_done() info_log_call = mock_info.call_args_list[-1] - self.assertFalse('Event pilight_received' in info_log_call) + assert not ('Event pilight_received' in info_log_call) class TestPilightCallrateThrottler(unittest.TestCase): @@ -368,7 +364,7 @@ class TestPilightCallrateThrottler(unittest.TestCase): for i in range(3): action(i) - self.assertEqual(runs, [0, 1, 2]) + assert runs == [0, 1, 2] def test_call_rate_delay_throttle_enabled(self): """Test that throttling actually work.""" @@ -381,7 +377,7 @@ class TestPilightCallrateThrottler(unittest.TestCase): for i in range(3): action(i) - self.assertEqual(runs, []) + assert runs == [] exp = [] now = dt_util.utcnow() @@ -391,4 +387,4 @@ class TestPilightCallrateThrottler(unittest.TestCase): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: shifted_time}) self.hass.block_till_done() - self.assertEqual(runs, exp) + assert runs == exp diff --git a/tests/components/test_plant.py b/tests/components/test_plant.py index 95167dd18..6118e3092 100644 --- a/tests/components/test_plant.py +++ b/tests/components/test_plant.py @@ -101,8 +101,8 @@ class TestPlant(unittest.TestCase): {ATTR_UNIT_OF_MEASUREMENT: 'us/cm'}) self.hass.block_till_done() state = self.hass.states.get('plant.'+plant_name) - self.assertEqual(STATE_PROBLEM, state.state) - self.assertEqual(5, state.attributes[plant.READING_MOISTURE]) + assert STATE_PROBLEM == state.state + assert 5 == state.attributes[plant.READING_MOISTURE] @pytest.mark.skipif(plant.ENABLE_LOAD_HISTORY is False, reason="tests for loading from DB are unstable, thus" @@ -132,10 +132,10 @@ class TestPlant(unittest.TestCase): self.hass.block_till_done() state = self.hass.states.get('plant.'+plant_name) - self.assertEqual(STATE_UNKNOWN, state.state) + assert STATE_UNKNOWN == state.state max_brightness = state.attributes.get( plant.ATTR_MAX_BRIGHTNESS_HISTORY) - self.assertEqual(30, max_brightness) + assert 30 == max_brightness def test_brightness_history(self): """Test the min_brightness check.""" @@ -149,19 +149,19 @@ class TestPlant(unittest.TestCase): {ATTR_UNIT_OF_MEASUREMENT: 'lux'}) self.hass.block_till_done() state = self.hass.states.get('plant.'+plant_name) - self.assertEqual(STATE_PROBLEM, state.state) + assert STATE_PROBLEM == state.state self.hass.states.set(BRIGHTNESS_ENTITY, 600, {ATTR_UNIT_OF_MEASUREMENT: 'lux'}) self.hass.block_till_done() state = self.hass.states.get('plant.'+plant_name) - self.assertEqual(STATE_OK, state.state) + assert STATE_OK == state.state self.hass.states.set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: 'lux'}) self.hass.block_till_done() state = self.hass.states.get('plant.'+plant_name) - self.assertEqual(STATE_OK, state.state) + assert STATE_OK == state.state class TestDailyHistory(unittest.TestCase): @@ -170,7 +170,7 @@ class TestDailyHistory(unittest.TestCase): def test_no_data(self): """Test with empty history.""" dh = plant.DailyHistory(3) - self.assertIsNone(dh.max) + assert dh.max is None def test_one_day(self): """Test storing data for the same day.""" @@ -179,8 +179,8 @@ class TestDailyHistory(unittest.TestCase): for i in range(len(values)): dh.add_measurement(values[i]) max_value = max(values[0:i+1]) - self.assertEqual(1, len(dh._days)) - self.assertEqual(dh.max, max_value) + assert 1 == len(dh._days) + assert dh.max == max_value def test_multiple_days(self): """Test storing data for different days.""" @@ -195,4 +195,4 @@ class TestDailyHistory(unittest.TestCase): for i in range(len(days)): dh.add_measurement(values[i], days[i]) - self.assertEqual(max_values[i], dh.max) + assert max_values[i] == dh.max diff --git a/tests/components/test_proximity.py b/tests/components/test_proximity.py index f69ace460..ca8915cd0 100644 --- a/tests/components/test_proximity.py +++ b/tests/components/test_proximity.py @@ -58,7 +58,7 @@ class TestProximity(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, DOMAIN, config)) + assert setup_component(self.hass, DOMAIN, config) proximities = ['home', 'work'] @@ -93,7 +93,7 @@ class TestProximity(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, DOMAIN, config)) + assert setup_component(self.hass, DOMAIN, config) def test_proximity(self): """Test the proximity.""" @@ -112,7 +112,7 @@ class TestProximity(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, DOMAIN, config)) + assert setup_component(self.hass, DOMAIN, config) state = self.hass.states.get('proximity.home') assert state.state == 'not set' @@ -140,7 +140,7 @@ class TestProximity(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, DOMAIN, config)) + assert setup_component(self.hass, DOMAIN, config) self.hass.states.set( 'device_tracker.test1', 'home', @@ -172,7 +172,7 @@ class TestProximity(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, DOMAIN, config)) + assert setup_component(self.hass, DOMAIN, config) self.hass.states.set( 'device_tracker.test1', 'home', @@ -212,7 +212,7 @@ class TestProximity(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, DOMAIN, config)) + assert setup_component(self.hass, DOMAIN, config) self.hass.states.set( 'device_tracker.test1', 'not_home', @@ -243,7 +243,7 @@ class TestProximity(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, DOMAIN, config)) + assert setup_component(self.hass, DOMAIN, config) self.hass.states.set( 'device_tracker.test1', 'not_home', @@ -285,7 +285,7 @@ class TestProximity(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, DOMAIN, config)) + assert setup_component(self.hass, DOMAIN, config) self.hass.states.set( 'device_tracker.test1', 'not_home', @@ -327,7 +327,7 @@ class TestProximity(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, DOMAIN, config)) + assert setup_component(self.hass, DOMAIN, config) self.hass.states.set( 'device_tracker.test1', 'work', @@ -356,7 +356,7 @@ class TestProximity(unittest.TestCase): } } - self.assertTrue(setup_component(self.hass, DOMAIN, config)) + assert setup_component(self.hass, DOMAIN, config) self.hass.states.set( 'device_tracker.test1', 'not_home', diff --git a/tests/components/test_remember_the_milk.py b/tests/components/test_remember_the_milk.py index d9db61efd..89f19f624 100644 --- a/tests/components/test_remember_the_milk.py +++ b/tests/components/test_remember_the_milk.py @@ -42,14 +42,14 @@ class TestConfiguration(unittest.TestCase): patch.object(rtm.RememberTheMilkConfiguration, 'save_config'): config = rtm.RememberTheMilkConfiguration(self.hass) config.set_token(self.profile, self.token) - self.assertEqual(config.get_token(self.profile), self.token) + assert config.get_token(self.profile) == self.token def test_load_config(self): """Test loading an existing token from the file.""" with patch("builtins.open", mock_open(read_data=self.json_string)), \ patch("os.path.isfile", Mock(return_value=True)): config = rtm.RememberTheMilkConfiguration(self.hass) - self.assertEqual(config.get_token(self.profile), self.token) + assert config.get_token(self.profile) == self.token def test_invalid_data(self): """Test starts with invalid data and should not raise an exception.""" @@ -57,7 +57,7 @@ class TestConfiguration(unittest.TestCase): mock_open(read_data='random characters')),\ patch("os.path.isfile", Mock(return_value=True)): config = rtm.RememberTheMilkConfiguration(self.hass) - self.assertIsNotNone(config) + assert config is not None def test_id_map(self): """Test the hass to rtm task is mapping.""" @@ -70,18 +70,18 @@ class TestConfiguration(unittest.TestCase): patch.object(rtm.RememberTheMilkConfiguration, 'save_config'): config = rtm.RememberTheMilkConfiguration(self.hass) - self.assertEqual(None, config.get_rtm_id(self.profile, hass_id)) + assert config.get_rtm_id(self.profile, hass_id) is None config.set_rtm_id(self.profile, hass_id, list_id, timeseries_id, rtm_id) - self.assertEqual((list_id, timeseries_id, rtm_id), - config.get_rtm_id(self.profile, hass_id)) + assert (list_id, timeseries_id, rtm_id) == \ + config.get_rtm_id(self.profile, hass_id) config.delete_rtm_id(self.profile, hass_id) - self.assertEqual(None, config.get_rtm_id(self.profile, hass_id)) + assert config.get_rtm_id(self.profile, hass_id) is None def test_load_key_map(self): """Test loading an existing key map from the file.""" with patch("builtins.open", mock_open(read_data=self.json_string)), \ patch("os.path.isfile", Mock(return_value=True)): config = rtm.RememberTheMilkConfiguration(self.hass) - self.assertEqual(('0', '1', '2',), - config.get_rtm_id(self.profile, "1234")) + assert ('0', '1', '2',) == \ + config.get_rtm_id(self.profile, "1234") diff --git a/tests/components/test_rfxtrx.py b/tests/components/test_rfxtrx.py index 93bf0b16d..d5c877e42 100644 --- a/tests/components/test_rfxtrx.py +++ b/tests/components/test_rfxtrx.py @@ -28,65 +28,65 @@ class TestRFXTRX(unittest.TestCase): def test_default_config(self): """Test configuration.""" - self.assertTrue(setup_component(self.hass, 'rfxtrx', { + assert setup_component(self.hass, 'rfxtrx', { 'rfxtrx': { 'device': '/dev/serial/by-id/usb' + '-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0', 'dummy': True} - })) + }) - self.assertTrue(setup_component(self.hass, 'sensor', { + assert setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'automatic_add': True, - 'devices': {}}})) + 'devices': {}}}) - self.assertEqual(len(rfxtrx.RFXOBJECT.sensors()), 2) + assert len(rfxtrx.RFXOBJECT.sensors()) == 2 def test_valid_config(self): """Test configuration.""" - self.assertTrue(setup_component(self.hass, 'rfxtrx', { + assert setup_component(self.hass, 'rfxtrx', { 'rfxtrx': { 'device': '/dev/serial/by-id/usb' + '-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0', - 'dummy': True}})) + 'dummy': True}}) def test_valid_config2(self): """Test configuration.""" - self.assertTrue(setup_component(self.hass, 'rfxtrx', { + assert setup_component(self.hass, 'rfxtrx', { 'rfxtrx': { 'device': '/dev/serial/by-id/usb' + '-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0', 'dummy': True, - 'debug': True}})) + 'debug': True}}) def test_invalid_config(self): """Test configuration.""" - self.assertFalse(setup_component(self.hass, 'rfxtrx', { + assert not setup_component(self.hass, 'rfxtrx', { 'rfxtrx': {} - })) + }) - self.assertFalse(setup_component(self.hass, 'rfxtrx', { + assert not setup_component(self.hass, 'rfxtrx', { 'rfxtrx': { 'device': '/dev/serial/by-id/usb' + '-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0', - 'invalid_key': True}})) + 'invalid_key': True}}) def test_fire_event(self): """Test fire event.""" - self.assertTrue(setup_component(self.hass, 'rfxtrx', { + assert setup_component(self.hass, 'rfxtrx', { 'rfxtrx': { 'device': '/dev/serial/by-id/usb' + '-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0', 'dummy': True} - })) - self.assertTrue(setup_component(self.hass, 'switch', { + }) + assert setup_component(self.hass, 'switch', { 'switch': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'0b1100cd0213c7f210010f51': { 'name': 'Test', rfxtrx.ATTR_FIREEVENT: True} - }}})) + }}}) calls = [] @@ -99,9 +99,9 @@ class TestRFXTRX(unittest.TestCase): self.hass.block_till_done() entity = rfxtrx.RFX_DEVICES['213c7f216'] - self.assertEqual('Test', entity.name) - self.assertEqual('off', entity.state) - self.assertTrue(entity.should_fire_event) + assert 'Test' == entity.name + assert 'off' == entity.state + assert entity.should_fire_event event = rfxtrx.get_rfx_object('0b1100cd0213c7f210010f51') event.data = bytearray([0x0b, 0x11, 0x00, 0x10, 0x01, 0x18, @@ -109,29 +109,29 @@ class TestRFXTRX(unittest.TestCase): rfxtrx.RECEIVED_EVT_SUBSCRIBERS[0](event) self.hass.block_till_done() - self.assertEqual(event.values['Command'], "On") - self.assertEqual('on', entity.state) - self.assertEqual(self.hass.states.get('switch.test').state, 'on') - self.assertEqual(1, len(calls)) - self.assertEqual(calls[0].data, - {'entity_id': 'switch.test', 'state': 'on'}) + assert event.values['Command'] == "On" + assert 'on' == entity.state + assert self.hass.states.get('switch.test').state == 'on' + assert 1 == len(calls) + assert calls[0].data == \ + {'entity_id': 'switch.test', 'state': 'on'} def test_fire_event_sensor(self): """Test fire event.""" - self.assertTrue(setup_component(self.hass, 'rfxtrx', { + assert setup_component(self.hass, 'rfxtrx', { 'rfxtrx': { 'device': '/dev/serial/by-id/usb' + '-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0', 'dummy': True} - })) - self.assertTrue(setup_component(self.hass, 'sensor', { + }) + assert setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'0a520802060100ff0e0269': { 'name': 'Test', rfxtrx.ATTR_FIREEVENT: True} - }}})) + }}}) calls = [] @@ -147,6 +147,6 @@ class TestRFXTRX(unittest.TestCase): rfxtrx.RECEIVED_EVT_SUBSCRIBERS[0](event) self.hass.block_till_done() - self.assertEqual(1, len(calls)) - self.assertEqual(calls[0].data, - {'entity_id': 'sensor.test'}) + assert 1 == len(calls) + assert calls[0].data == \ + {'entity_id': 'sensor.test'} diff --git a/tests/components/test_ring.py b/tests/components/test_ring.py index 7b974686a..223f3df70 100644 --- a/tests/components/test_ring.py +++ b/tests/components/test_ring.py @@ -47,7 +47,7 @@ class TestRing(unittest.TestCase): mock.post('https://api.ring.com/clients_api/session', text=load_fixture('ring_session.json')) response = ring.setup(self.hass, self.config) - self.assertTrue(response) + assert response @requests_mock.Mocker() def test_setup_component_no_login(self, mock): diff --git a/tests/components/test_script.py b/tests/components/test_script.py index 43727b6d5..5b7d0dfb7 100644 --- a/tests/components/test_script.py +++ b/tests/components/test_script.py @@ -90,7 +90,7 @@ class TestScriptComponent(unittest.TestCase): 'script': value }), 'Script loaded with wrong config {}'.format(value) - self.assertEqual(0, len(self.hass.states.entity_ids('script'))) + assert 0 == len(self.hass.states.entity_ids('script')) def test_turn_on_service(self): """Verify that the turn_on service.""" @@ -120,18 +120,18 @@ class TestScriptComponent(unittest.TestCase): turn_on(self.hass, ENTITY_ID) self.hass.block_till_done() - self.assertTrue(script.is_on(self.hass, ENTITY_ID)) - self.assertEqual(0, len(events)) + assert script.is_on(self.hass, ENTITY_ID) + assert 0 == len(events) # Calling turn_on a second time should not advance the script turn_on(self.hass, ENTITY_ID) self.hass.block_till_done() - self.assertEqual(0, len(events)) + assert 0 == len(events) turn_off(self.hass, ENTITY_ID) self.hass.block_till_done() - self.assertFalse(script.is_on(self.hass, ENTITY_ID)) - self.assertEqual(0, len(events)) + assert not script.is_on(self.hass, ENTITY_ID) + assert 0 == len(events) state = self.hass.states.get('group.all_scripts') assert state is not None @@ -165,13 +165,13 @@ class TestScriptComponent(unittest.TestCase): toggle(self.hass, ENTITY_ID) self.hass.block_till_done() - self.assertTrue(script.is_on(self.hass, ENTITY_ID)) - self.assertEqual(0, len(events)) + assert script.is_on(self.hass, ENTITY_ID) + assert 0 == len(events) toggle(self.hass, ENTITY_ID) self.hass.block_till_done() - self.assertFalse(script.is_on(self.hass, ENTITY_ID)) - self.assertEqual(0, len(events)) + assert not script.is_on(self.hass, ENTITY_ID) + assert 0 == len(events) def test_passing_variables(self): """Test different ways of passing in variables.""" diff --git a/tests/components/test_shell_command.py b/tests/components/test_shell_command.py index e945befbb..bab891c07 100644 --- a/tests/components/test_shell_command.py +++ b/tests/components/test_shell_command.py @@ -61,23 +61,21 @@ class TestShellCommand(unittest.TestCase): self.hass.services.call('shell_command', 'test_service', blocking=True) self.hass.block_till_done() - self.assertTrue(os.path.isfile(path)) + assert os.path.isfile(path) def test_config_not_dict(self): """Test that setup fails if config is not a dict.""" - self.assertFalse( - setup_component(self.hass, shell_command.DOMAIN, { + assert not setup_component(self.hass, shell_command.DOMAIN, { shell_command.DOMAIN: ['some', 'weird', 'list'] - })) + }) def test_config_not_valid_service_names(self): """Test that setup fails if config contains invalid service names.""" - self.assertFalse( - setup_component(self.hass, shell_command.DOMAIN, { + assert not setup_component(self.hass, shell_command.DOMAIN, { shell_command.DOMAIN: { 'this is invalid because space': 'touch bla.txt' } - })) + }) @patch('homeassistant.components.shell_command.asyncio.subprocess' '.create_subprocess_shell') @@ -85,14 +83,13 @@ class TestShellCommand(unittest.TestCase): """Ensure shell_commands without templates get rendered properly.""" mock_call.return_value = mock_process_creator(error=False) - self.assertTrue( - setup_component( + assert setup_component( self.hass, shell_command.DOMAIN, { shell_command.DOMAIN: { 'test_service': "ls /bin" } - })) + }) self.hass.services.call('shell_command', 'test_service', blocking=True) @@ -100,8 +97,8 @@ class TestShellCommand(unittest.TestCase): self.hass.block_till_done() cmd = mock_call.mock_calls[0][1][0] - self.assertEqual(1, mock_call.call_count) - self.assertEqual('ls /bin', cmd) + assert 1 == mock_call.call_count + assert 'ls /bin' == cmd @patch('homeassistant.components.shell_command.asyncio.subprocess' '.create_subprocess_exec') @@ -109,13 +106,12 @@ class TestShellCommand(unittest.TestCase): """Ensure shell_commands with templates get rendered properly.""" self.hass.states.set('sensor.test_state', 'Works') mock_call.return_value = mock_process_creator(error=False) - self.assertTrue( - setup_component(self.hass, shell_command.DOMAIN, { + assert setup_component(self.hass, shell_command.DOMAIN, { shell_command.DOMAIN: { 'test_service': ("ls /bin {{ states.sensor" ".test_state.state }}") } - })) + }) self.hass.services.call('shell_command', 'test_service', blocking=True) @@ -123,8 +119,8 @@ class TestShellCommand(unittest.TestCase): self.hass.block_till_done() cmd = mock_call.mock_calls[0][1] - self.assertEqual(1, mock_call.call_count) - self.assertEqual(('ls', '/bin', 'Works'), cmd) + assert 1 == mock_call.call_count + assert ('ls', '/bin', 'Works') == cmd @patch('homeassistant.components.shell_command.asyncio.subprocess' '.create_subprocess_shell') @@ -134,55 +130,52 @@ class TestShellCommand(unittest.TestCase): mock_call.return_value = mock_process_creator(error=True) with tempfile.TemporaryDirectory() as tempdirname: path = os.path.join(tempdirname, 'called.txt') - self.assertTrue( - setup_component(self.hass, shell_command.DOMAIN, { + assert setup_component(self.hass, shell_command.DOMAIN, { shell_command.DOMAIN: { 'test_service': "touch {}".format(path) } - })) + }) self.hass.services.call('shell_command', 'test_service', blocking=True) self.hass.block_till_done() - self.assertEqual(1, mock_call.call_count) - self.assertEqual(1, mock_error.call_count) - self.assertFalse(os.path.isfile(path)) + assert 1 == mock_call.call_count + assert 1 == mock_error.call_count + assert not os.path.isfile(path) @patch('homeassistant.components.shell_command._LOGGER.debug') def test_stdout_captured(self, mock_output): """Test subprocess that has stdout.""" test_phrase = "I have output" - self.assertTrue( - setup_component(self.hass, shell_command.DOMAIN, { + assert setup_component(self.hass, shell_command.DOMAIN, { shell_command.DOMAIN: { 'test_service': "echo {}".format(test_phrase) } - })) + }) self.hass.services.call('shell_command', 'test_service', blocking=True) self.hass.block_till_done() - self.assertEqual(1, mock_output.call_count) - self.assertEqual(test_phrase.encode() + b'\n', - mock_output.call_args_list[0][0][-1]) + assert 1 == mock_output.call_count + assert test_phrase.encode() + b'\n' == \ + mock_output.call_args_list[0][0][-1] @patch('homeassistant.components.shell_command._LOGGER.debug') def test_stderr_captured(self, mock_output): """Test subprocess that has stderr.""" test_phrase = "I have error" - self.assertTrue( - setup_component(self.hass, shell_command.DOMAIN, { + assert setup_component(self.hass, shell_command.DOMAIN, { shell_command.DOMAIN: { 'test_service': ">&2 echo {}".format(test_phrase) } - })) + }) self.hass.services.call('shell_command', 'test_service', blocking=True) self.hass.block_till_done() - self.assertEqual(1, mock_output.call_count) - self.assertEqual(test_phrase.encode() + b'\n', - mock_output.call_args_list[0][0][-1]) + assert 1 == mock_output.call_count + assert test_phrase.encode() + b'\n' == \ + mock_output.call_args_list[0][0][-1] diff --git a/tests/components/test_sleepiq.py b/tests/components/test_sleepiq.py index becf897a8..d3235cbd8 100644 --- a/tests/components/test_sleepiq.py +++ b/tests/components/test_sleepiq.py @@ -66,7 +66,7 @@ class TestSleepIQ(unittest.TestCase): json=load_fixture('sleepiq-login-failed.json')) response = sleepiq.setup(self.hass, self.config) - self.assertFalse(response) + assert not response def test_setup_component_no_login(self): """Test the setup when no login is configured.""" diff --git a/tests/components/test_splunk.py b/tests/components/test_splunk.py index 173c822dd..a39143f14 100644 --- a/tests/components/test_splunk.py +++ b/tests/components/test_splunk.py @@ -36,10 +36,10 @@ class TestSplunk(unittest.TestCase): } self.hass.bus.listen = mock.MagicMock() - self.assertTrue(setup_component(self.hass, splunk.DOMAIN, config)) - self.assertTrue(self.hass.bus.listen.called) - self.assertEqual(EVENT_STATE_CHANGED, - self.hass.bus.listen.call_args_list[0][0][0]) + assert setup_component(self.hass, splunk.DOMAIN, config) + assert self.hass.bus.listen.called + assert EVENT_STATE_CHANGED == \ + self.hass.bus.listen.call_args_list[0][0][0] def test_setup_config_defaults(self): """Test setup with defaults.""" @@ -51,10 +51,10 @@ class TestSplunk(unittest.TestCase): } self.hass.bus.listen = mock.MagicMock() - self.assertTrue(setup_component(self.hass, splunk.DOMAIN, config)) - self.assertTrue(self.hass.bus.listen.called) - self.assertEqual(EVENT_STATE_CHANGED, - self.hass.bus.listen.call_args_list[0][0][0]) + assert setup_component(self.hass, splunk.DOMAIN, config) + assert self.hass.bus.listen.called + assert EVENT_STATE_CHANGED == \ + self.hass.bus.listen.call_args_list[0][0][0] def _setup(self, mock_requests): """Test the setup.""" @@ -113,13 +113,11 @@ class TestSplunk(unittest.TestCase): payload = {'host': 'http://host:8088/services/collector/event', 'event': body} self.handler_method(event) - self.assertEqual(self.mock_post.call_count, 1) - self.assertEqual( - self.mock_post.call_args, + assert self.mock_post.call_count == 1 + assert self.mock_post.call_args == \ mock.call( payload['host'], data=json.dumps(payload), headers={'Authorization': 'Splunk secret'}, timeout=10 ) - ) self.mock_post.reset_mock() diff --git a/tests/components/test_statsd.py b/tests/components/test_statsd.py index 6bd00e506..c267f335b 100644 --- a/tests/components/test_statsd.py +++ b/tests/components/test_statsd.py @@ -10,6 +10,7 @@ import homeassistant.components.statsd as statsd from homeassistant.const import (STATE_ON, STATE_OFF, EVENT_STATE_CHANGED) from tests.common import get_test_home_assistant +import pytest class TestStatsd(unittest.TestCase): @@ -31,9 +32,9 @@ class TestStatsd(unittest.TestCase): } } - with self.assertRaises(vol.Invalid): + with pytest.raises(vol.Invalid): statsd.CONFIG_SCHEMA(None) - with self.assertRaises(vol.Invalid): + with pytest.raises(vol.Invalid): statsd.CONFIG_SCHEMA(config) @mock.patch('statsd.StatsClient') @@ -48,16 +49,14 @@ class TestStatsd(unittest.TestCase): } } self.hass.bus.listen = mock.MagicMock() - self.assertTrue(setup_component(self.hass, statsd.DOMAIN, config)) - self.assertEqual(mock_connection.call_count, 1) - self.assertEqual( - mock_connection.call_args, + assert setup_component(self.hass, statsd.DOMAIN, config) + assert mock_connection.call_count == 1 + assert mock_connection.call_args == \ mock.call(host='host', port=123, prefix='foo') - ) - self.assertTrue(self.hass.bus.listen.called) - self.assertEqual(EVENT_STATE_CHANGED, - self.hass.bus.listen.call_args_list[0][0][0]) + assert self.hass.bus.listen.called + assert EVENT_STATE_CHANGED == \ + self.hass.bus.listen.call_args_list[0][0][0] @mock.patch('statsd.StatsClient') def test_statsd_setup_defaults(self, mock_connection): @@ -72,13 +71,11 @@ class TestStatsd(unittest.TestCase): config['statsd'][statsd.CONF_PREFIX] = statsd.DEFAULT_PREFIX self.hass.bus.listen = mock.MagicMock() - self.assertTrue(setup_component(self.hass, statsd.DOMAIN, config)) - self.assertEqual(mock_connection.call_count, 1) - self.assertEqual( - mock_connection.call_args, + assert setup_component(self.hass, statsd.DOMAIN, config) + assert mock_connection.call_count == 1 + assert mock_connection.call_args == \ mock.call(host='host', port=8125, prefix='hass') - ) - self.assertTrue(self.hass.bus.listen.called) + assert self.hass.bus.listen.called @mock.patch('statsd.StatsClient') def test_event_listener_defaults(self, mock_client): @@ -94,7 +91,7 @@ class TestStatsd(unittest.TestCase): self.hass.bus.listen = mock.MagicMock() setup_component(self.hass, statsd.DOMAIN, config) - self.assertTrue(self.hass.bus.listen.called) + assert self.hass.bus.listen.called handler_method = self.hass.bus.listen.call_args_list[0][0][1] valid = {'1': 1, @@ -112,18 +109,16 @@ class TestStatsd(unittest.TestCase): mock_client.return_value.gauge.reset_mock() - self.assertEqual(mock_client.return_value.incr.call_count, 1) - self.assertEqual( - mock_client.return_value.incr.call_args, + assert mock_client.return_value.incr.call_count == 1 + assert mock_client.return_value.incr.call_args == \ mock.call(state.entity_id, rate=statsd.DEFAULT_RATE) - ) mock_client.return_value.incr.reset_mock() for invalid in ('foo', '', object): handler_method(mock.MagicMock(data={ 'new_state': ha.State('domain.test', invalid, {})})) - self.assertFalse(mock_client.return_value.gauge.called) - self.assertTrue(mock_client.return_value.incr.called) + assert not mock_client.return_value.gauge.called + assert mock_client.return_value.incr.called @mock.patch('statsd.StatsClient') def test_event_listener_attr_details(self, mock_client): @@ -139,7 +134,7 @@ class TestStatsd(unittest.TestCase): self.hass.bus.listen = mock.MagicMock() setup_component(self.hass, statsd.DOMAIN, config) - self.assertTrue(self.hass.bus.listen.called) + assert self.hass.bus.listen.called handler_method = self.hass.bus.listen.call_args_list[0][0][1] valid = {'1': 1, @@ -159,15 +154,13 @@ class TestStatsd(unittest.TestCase): mock_client.return_value.gauge.reset_mock() - self.assertEqual(mock_client.return_value.incr.call_count, 1) - self.assertEqual( - mock_client.return_value.incr.call_args, + assert mock_client.return_value.incr.call_count == 1 + assert mock_client.return_value.incr.call_args == \ mock.call(state.entity_id, rate=statsd.DEFAULT_RATE) - ) mock_client.return_value.incr.reset_mock() for invalid in ('foo', '', object): handler_method(mock.MagicMock(data={ 'new_state': ha.State('domain.test', invalid, {})})) - self.assertFalse(mock_client.return_value.gauge.called) - self.assertTrue(mock_client.return_value.incr.called) + assert not mock_client.return_value.gauge.called + assert mock_client.return_value.incr.called diff --git a/tests/components/test_sun.py b/tests/components/test_sun.py index aa94bf2bd..2833efa62 100644 --- a/tests/components/test_sun.py +++ b/tests/components/test_sun.py @@ -91,18 +91,18 @@ class TestSun(unittest.TestCase): break mod += 1 - self.assertEqual(next_dawn, dt_util.parse_datetime( - state.attributes[sun.STATE_ATTR_NEXT_DAWN])) - self.assertEqual(next_dusk, dt_util.parse_datetime( - state.attributes[sun.STATE_ATTR_NEXT_DUSK])) - self.assertEqual(next_midnight, dt_util.parse_datetime( - state.attributes[sun.STATE_ATTR_NEXT_MIDNIGHT])) - self.assertEqual(next_noon, dt_util.parse_datetime( - state.attributes[sun.STATE_ATTR_NEXT_NOON])) - self.assertEqual(next_rising, dt_util.parse_datetime( - state.attributes[sun.STATE_ATTR_NEXT_RISING])) - self.assertEqual(next_setting, dt_util.parse_datetime( - state.attributes[sun.STATE_ATTR_NEXT_SETTING])) + assert next_dawn == dt_util.parse_datetime( + state.attributes[sun.STATE_ATTR_NEXT_DAWN]) + assert next_dusk == dt_util.parse_datetime( + state.attributes[sun.STATE_ATTR_NEXT_DUSK]) + assert next_midnight == dt_util.parse_datetime( + state.attributes[sun.STATE_ATTR_NEXT_MIDNIGHT]) + assert next_noon == dt_util.parse_datetime( + state.attributes[sun.STATE_ATTR_NEXT_NOON]) + assert next_rising == dt_util.parse_datetime( + state.attributes[sun.STATE_ATTR_NEXT_RISING]) + assert next_setting == dt_util.parse_datetime( + state.attributes[sun.STATE_ATTR_NEXT_SETTING]) def test_state_change(self): """Test if the state changes at next setting/rising.""" @@ -117,18 +117,18 @@ class TestSun(unittest.TestCase): test_time = dt_util.parse_datetime( self.hass.states.get(sun.ENTITY_ID) .attributes[sun.STATE_ATTR_NEXT_RISING]) - self.assertIsNotNone(test_time) + assert test_time is not None - self.assertEqual(sun.STATE_BELOW_HORIZON, - self.hass.states.get(sun.ENTITY_ID).state) + assert sun.STATE_BELOW_HORIZON == \ + self.hass.states.get(sun.ENTITY_ID).state self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: test_time + timedelta(seconds=5)}) self.hass.block_till_done() - self.assertEqual(sun.STATE_ABOVE_HORIZON, - self.hass.states.get(sun.ENTITY_ID).state) + assert sun.STATE_ABOVE_HORIZON == \ + self.hass.states.get(sun.ENTITY_ID).state def test_norway_in_june(self): """Test location in Norway where the sun doesn't set in summer.""" diff --git a/tests/components/test_vultr.py b/tests/components/test_vultr.py index 725768f93..15e9864f2 100644 --- a/tests/components/test_vultr.py +++ b/tests/components/test_vultr.py @@ -39,7 +39,7 @@ class TestVultr(unittest.TestCase): return_value=json.loads( load_fixture('vultr_server_list.json'))): response = vultr.setup(self.hass, self.config) - self.assertTrue(response) + assert response def test_setup_no_api_key(self): """Test failed setup with missing API Key.""" diff --git a/tests/components/test_weblink.py b/tests/components/test_weblink.py index 8e71c89cd..727db5c01 100644 --- a/tests/components/test_weblink.py +++ b/tests/components/test_weblink.py @@ -20,15 +20,15 @@ class TestComponentWeblink(unittest.TestCase): def test_bad_config(self): """Test if new entity is created.""" - self.assertFalse(setup_component(self.hass, 'weblink', { + assert not setup_component(self.hass, 'weblink', { 'weblink': { 'entities': [{}], } - })) + }) def test_bad_config_relative_url(self): """Test if new entity is created.""" - self.assertFalse(setup_component(self.hass, 'weblink', { + assert not setup_component(self.hass, 'weblink', { 'weblink': { 'entities': [ { @@ -37,11 +37,11 @@ class TestComponentWeblink(unittest.TestCase): }, ], } - })) + }) def test_bad_config_relative_file(self): """Test if new entity is created.""" - self.assertFalse(setup_component(self.hass, 'weblink', { + assert not setup_component(self.hass, 'weblink', { 'weblink': { 'entities': [ { @@ -50,11 +50,11 @@ class TestComponentWeblink(unittest.TestCase): }, ], } - })) + }) def test_good_config_absolute_path(self): """Test if new entity is created.""" - self.assertTrue(setup_component(self.hass, 'weblink', { + assert setup_component(self.hass, 'weblink', { 'weblink': { 'entities': [ { @@ -63,11 +63,11 @@ class TestComponentWeblink(unittest.TestCase): }, ], } - })) + }) def test_good_config_path_short(self): """Test if new entity is created.""" - self.assertTrue(setup_component(self.hass, 'weblink', { + assert setup_component(self.hass, 'weblink', { 'weblink': { 'entities': [ { @@ -76,11 +76,11 @@ class TestComponentWeblink(unittest.TestCase): }, ], } - })) + }) def test_good_config_path_directory(self): """Test if new entity is created.""" - self.assertTrue(setup_component(self.hass, 'weblink', { + assert setup_component(self.hass, 'weblink', { 'weblink': { 'entities': [ { @@ -89,11 +89,11 @@ class TestComponentWeblink(unittest.TestCase): }, ], } - })) + }) def test_good_config_ftp_link(self): """Test if new entity is created.""" - self.assertTrue(setup_component(self.hass, 'weblink', { + assert setup_component(self.hass, 'weblink', { 'weblink': { 'entities': [ { @@ -102,11 +102,11 @@ class TestComponentWeblink(unittest.TestCase): }, ], } - })) + }) def test_entities_get_created(self): """Test if new entity is created.""" - self.assertTrue(setup_component(self.hass, weblink.DOMAIN, { + assert setup_component(self.hass, weblink.DOMAIN, { weblink.DOMAIN: { 'entities': [ { @@ -115,7 +115,7 @@ class TestComponentWeblink(unittest.TestCase): }, ] } - })) + }) state = self.hass.states.get('weblink.my_router') diff --git a/tests/components/timer/test_init.py b/tests/components/timer/test_init.py index 5b36273f0..afd2b1412 100644 --- a/tests/components/timer/test_init.py +++ b/tests/components/timer/test_init.py @@ -43,8 +43,7 @@ class TestTimer(unittest.TestCase): ] for cfg in invalid_configs: - self.assertFalse( - setup_component(self.hass, DOMAIN, {DOMAIN: cfg})) + assert not setup_component(self.hass, DOMAIN, {DOMAIN: cfg}) def test_config_options(self): """Test configuration options.""" @@ -66,24 +65,24 @@ class TestTimer(unittest.TestCase): assert setup_component(self.hass, 'timer', config) self.hass.block_till_done() - self.assertEqual(count_start + 2, len(self.hass.states.entity_ids())) + assert count_start + 2 == len(self.hass.states.entity_ids()) self.hass.block_till_done() state_1 = self.hass.states.get('timer.test_1') state_2 = self.hass.states.get('timer.test_2') - self.assertIsNotNone(state_1) - self.assertIsNotNone(state_2) + assert state_1 is not None + assert state_2 is not None - self.assertEqual(STATUS_IDLE, state_1.state) - self.assertNotIn(ATTR_ICON, state_1.attributes) - self.assertNotIn(ATTR_FRIENDLY_NAME, state_1.attributes) + assert STATUS_IDLE == state_1.state + assert ATTR_ICON not in state_1.attributes + assert ATTR_FRIENDLY_NAME not in state_1.attributes - self.assertEqual(STATUS_IDLE, state_2.state) - self.assertEqual('Hello World', - state_2.attributes.get(ATTR_FRIENDLY_NAME)) - self.assertEqual('mdi:work', state_2.attributes.get(ATTR_ICON)) - self.assertEqual('0:00:10', state_2.attributes.get(ATTR_DURATION)) + assert STATUS_IDLE == state_2.state + assert 'Hello World' == \ + state_2.attributes.get(ATTR_FRIENDLY_NAME) + assert 'mdi:work' == state_2.attributes.get(ATTR_ICON) + assert '0:00:10' == state_2.attributes.get(ATTR_DURATION) @asyncio.coroutine diff --git a/tests/components/vacuum/test_demo.py b/tests/components/vacuum/test_demo.py index f88908ecc..e0b560bbb 100644 --- a/tests/components/vacuum/test_demo.py +++ b/tests/components/vacuum/test_demo.py @@ -34,8 +34,8 @@ class TestVacuumDemo(unittest.TestCase): def setUp(self): # pylint: disable=invalid-name """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() - self.assertTrue(setup_component( - self.hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: 'demo'}})) + assert setup_component( + self.hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: 'demo'}}) def tearDown(self): # pylint: disable=invalid-name """Stop down everything that was started.""" @@ -44,243 +44,243 @@ class TestVacuumDemo(unittest.TestCase): def test_supported_features(self): """Test vacuum supported features.""" state = self.hass.states.get(ENTITY_VACUUM_COMPLETE) - self.assertEqual(2047, state.attributes.get(ATTR_SUPPORTED_FEATURES)) - self.assertEqual("Charging", state.attributes.get(ATTR_STATUS)) - self.assertEqual(100, state.attributes.get(ATTR_BATTERY_LEVEL)) - self.assertEqual("medium", state.attributes.get(ATTR_FAN_SPEED)) - self.assertListEqual(FAN_SPEEDS, - state.attributes.get(ATTR_FAN_SPEED_LIST)) - self.assertEqual(STATE_OFF, state.state) + assert 2047 == state.attributes.get(ATTR_SUPPORTED_FEATURES) + assert "Charging" == state.attributes.get(ATTR_STATUS) + assert 100 == state.attributes.get(ATTR_BATTERY_LEVEL) + assert "medium" == state.attributes.get(ATTR_FAN_SPEED) + assert FAN_SPEEDS == \ + state.attributes.get(ATTR_FAN_SPEED_LIST) + assert STATE_OFF == state.state state = self.hass.states.get(ENTITY_VACUUM_MOST) - self.assertEqual(219, state.attributes.get(ATTR_SUPPORTED_FEATURES)) - self.assertEqual("Charging", state.attributes.get(ATTR_STATUS)) - self.assertEqual(100, state.attributes.get(ATTR_BATTERY_LEVEL)) - self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED)) - self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED_LIST)) - self.assertEqual(STATE_OFF, state.state) + assert 219 == state.attributes.get(ATTR_SUPPORTED_FEATURES) + assert "Charging" == state.attributes.get(ATTR_STATUS) + assert 100 == state.attributes.get(ATTR_BATTERY_LEVEL) + assert state.attributes.get(ATTR_FAN_SPEED) is None + assert state.attributes.get(ATTR_FAN_SPEED_LIST) is None + assert STATE_OFF == state.state state = self.hass.states.get(ENTITY_VACUUM_BASIC) - self.assertEqual(195, state.attributes.get(ATTR_SUPPORTED_FEATURES)) - self.assertEqual("Charging", state.attributes.get(ATTR_STATUS)) - self.assertEqual(100, state.attributes.get(ATTR_BATTERY_LEVEL)) - self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED)) - self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED_LIST)) - self.assertEqual(STATE_OFF, state.state) + assert 195 == state.attributes.get(ATTR_SUPPORTED_FEATURES) + assert "Charging" == state.attributes.get(ATTR_STATUS) + assert 100 == state.attributes.get(ATTR_BATTERY_LEVEL) + assert state.attributes.get(ATTR_FAN_SPEED) is None + assert state.attributes.get(ATTR_FAN_SPEED_LIST) is None + assert STATE_OFF == state.state state = self.hass.states.get(ENTITY_VACUUM_MINIMAL) - self.assertEqual(3, state.attributes.get(ATTR_SUPPORTED_FEATURES)) - self.assertEqual(None, state.attributes.get(ATTR_STATUS)) - self.assertEqual(None, state.attributes.get(ATTR_BATTERY_LEVEL)) - self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED)) - self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED_LIST)) - self.assertEqual(STATE_OFF, state.state) + assert 3 == state.attributes.get(ATTR_SUPPORTED_FEATURES) + assert state.attributes.get(ATTR_STATUS) is None + assert state.attributes.get(ATTR_BATTERY_LEVEL) is None + assert state.attributes.get(ATTR_FAN_SPEED) is None + assert state.attributes.get(ATTR_FAN_SPEED_LIST) is None + assert STATE_OFF == state.state state = self.hass.states.get(ENTITY_VACUUM_NONE) - self.assertEqual(0, state.attributes.get(ATTR_SUPPORTED_FEATURES)) - self.assertEqual(None, state.attributes.get(ATTR_STATUS)) - self.assertEqual(None, state.attributes.get(ATTR_BATTERY_LEVEL)) - self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED)) - self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED_LIST)) - self.assertEqual(STATE_OFF, state.state) + assert 0 == state.attributes.get(ATTR_SUPPORTED_FEATURES) + assert state.attributes.get(ATTR_STATUS) is None + assert state.attributes.get(ATTR_BATTERY_LEVEL) is None + assert state.attributes.get(ATTR_FAN_SPEED) is None + assert state.attributes.get(ATTR_FAN_SPEED_LIST) is None + assert STATE_OFF == state.state state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertEqual(13436, state.attributes.get(ATTR_SUPPORTED_FEATURES)) - self.assertEqual(STATE_DOCKED, state.state) - self.assertEqual(100, state.attributes.get(ATTR_BATTERY_LEVEL)) - self.assertEqual("medium", state.attributes.get(ATTR_FAN_SPEED)) - self.assertListEqual(FAN_SPEEDS, - state.attributes.get(ATTR_FAN_SPEED_LIST)) + assert 13436 == state.attributes.get(ATTR_SUPPORTED_FEATURES) + assert STATE_DOCKED == state.state + assert 100 == state.attributes.get(ATTR_BATTERY_LEVEL) + assert "medium" == state.attributes.get(ATTR_FAN_SPEED) + assert FAN_SPEEDS == \ + state.attributes.get(ATTR_FAN_SPEED_LIST) def test_methods(self): """Test if methods call the services as expected.""" self.hass.states.set(ENTITY_VACUUM_BASIC, STATE_ON) self.hass.block_till_done() - self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_BASIC)) + assert vacuum.is_on(self.hass, ENTITY_VACUUM_BASIC) self.hass.states.set(ENTITY_VACUUM_BASIC, STATE_OFF) self.hass.block_till_done() - self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_BASIC)) + assert not vacuum.is_on(self.hass, ENTITY_VACUUM_BASIC) self.hass.states.set(ENTITY_ID_ALL_VACUUMS, STATE_ON) self.hass.block_till_done() - self.assertTrue(vacuum.is_on(self.hass)) + assert vacuum.is_on(self.hass) self.hass.states.set(ENTITY_ID_ALL_VACUUMS, STATE_OFF) self.hass.block_till_done() - self.assertFalse(vacuum.is_on(self.hass)) + assert not vacuum.is_on(self.hass) common.turn_on(self.hass, ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() - self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE)) + assert vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE) common.turn_off(self.hass, ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() - self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE)) + assert not vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE) common.toggle(self.hass, ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() - self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE)) + assert vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE) common.start_pause(self.hass, ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() - self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE)) + assert not vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE) common.start_pause(self.hass, ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() - self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE)) + assert vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE) common.stop(self.hass, ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() - self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE)) + assert not vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE) state = self.hass.states.get(ENTITY_VACUUM_COMPLETE) - self.assertLess(state.attributes.get(ATTR_BATTERY_LEVEL), 100) - self.assertNotEqual("Charging", state.attributes.get(ATTR_STATUS)) + assert state.attributes.get(ATTR_BATTERY_LEVEL) < 100 + assert "Charging" != state.attributes.get(ATTR_STATUS) common.locate(self.hass, ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_COMPLETE) - self.assertIn("I'm over here", state.attributes.get(ATTR_STATUS)) + assert "I'm over here" in state.attributes.get(ATTR_STATUS) common.return_to_base(self.hass, ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_COMPLETE) - self.assertIn("Returning home", state.attributes.get(ATTR_STATUS)) + assert "Returning home" in state.attributes.get(ATTR_STATUS) common.set_fan_speed(self.hass, FAN_SPEEDS[-1], entity_id=ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_COMPLETE) - self.assertEqual(FAN_SPEEDS[-1], state.attributes.get(ATTR_FAN_SPEED)) + assert FAN_SPEEDS[-1] == state.attributes.get(ATTR_FAN_SPEED) common.clean_spot(self.hass, entity_id=ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_COMPLETE) - self.assertIn("spot", state.attributes.get(ATTR_STATUS)) - self.assertEqual(STATE_ON, state.state) + assert "spot" in state.attributes.get(ATTR_STATUS) + assert STATE_ON == state.state common.start(self.hass, ENTITY_VACUUM_STATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertEqual(STATE_CLEANING, state.state) + assert STATE_CLEANING == state.state common.pause(self.hass, ENTITY_VACUUM_STATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertEqual(STATE_PAUSED, state.state) + assert STATE_PAUSED == state.state common.stop(self.hass, ENTITY_VACUUM_STATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertEqual(STATE_IDLE, state.state) + assert STATE_IDLE == state.state state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertLess(state.attributes.get(ATTR_BATTERY_LEVEL), 100) - self.assertNotEqual(STATE_DOCKED, state.state) + assert state.attributes.get(ATTR_BATTERY_LEVEL) < 100 + assert STATE_DOCKED != state.state common.return_to_base(self.hass, ENTITY_VACUUM_STATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertEqual(STATE_RETURNING, state.state) + assert STATE_RETURNING == state.state common.set_fan_speed(self.hass, FAN_SPEEDS[-1], entity_id=ENTITY_VACUUM_STATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertEqual(FAN_SPEEDS[-1], state.attributes.get(ATTR_FAN_SPEED)) + assert FAN_SPEEDS[-1] == state.attributes.get(ATTR_FAN_SPEED) common.clean_spot(self.hass, entity_id=ENTITY_VACUUM_STATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertEqual(STATE_CLEANING, state.state) + assert STATE_CLEANING == state.state def test_unsupported_methods(self): """Test service calls for unsupported vacuums.""" self.hass.states.set(ENTITY_VACUUM_NONE, STATE_ON) self.hass.block_till_done() - self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE)) + assert vacuum.is_on(self.hass, ENTITY_VACUUM_NONE) common.turn_off(self.hass, ENTITY_VACUUM_NONE) self.hass.block_till_done() - self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE)) + assert vacuum.is_on(self.hass, ENTITY_VACUUM_NONE) common.stop(self.hass, ENTITY_VACUUM_NONE) self.hass.block_till_done() - self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE)) + assert vacuum.is_on(self.hass, ENTITY_VACUUM_NONE) self.hass.states.set(ENTITY_VACUUM_NONE, STATE_OFF) self.hass.block_till_done() - self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE)) + assert not vacuum.is_on(self.hass, ENTITY_VACUUM_NONE) common.turn_on(self.hass, ENTITY_VACUUM_NONE) self.hass.block_till_done() - self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE)) + assert not vacuum.is_on(self.hass, ENTITY_VACUUM_NONE) common.toggle(self.hass, ENTITY_VACUUM_NONE) self.hass.block_till_done() - self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE)) + assert not vacuum.is_on(self.hass, ENTITY_VACUUM_NONE) # Non supported methods: common.start_pause(self.hass, ENTITY_VACUUM_NONE) self.hass.block_till_done() - self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE)) + assert not vacuum.is_on(self.hass, ENTITY_VACUUM_NONE) common.locate(self.hass, ENTITY_VACUUM_NONE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_NONE) - self.assertIsNone(state.attributes.get(ATTR_STATUS)) + assert state.attributes.get(ATTR_STATUS) is None common.return_to_base(self.hass, ENTITY_VACUUM_NONE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_NONE) - self.assertIsNone(state.attributes.get(ATTR_STATUS)) + assert state.attributes.get(ATTR_STATUS) is None common.set_fan_speed(self.hass, FAN_SPEEDS[-1], entity_id=ENTITY_VACUUM_NONE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_NONE) - self.assertNotEqual(FAN_SPEEDS[-1], - state.attributes.get(ATTR_FAN_SPEED)) + assert FAN_SPEEDS[-1] != \ + state.attributes.get(ATTR_FAN_SPEED) common.clean_spot(self.hass, entity_id=ENTITY_VACUUM_BASIC) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_BASIC) - self.assertNotIn("spot", state.attributes.get(ATTR_STATUS)) - self.assertEqual(STATE_OFF, state.state) + assert "spot" not in state.attributes.get(ATTR_STATUS) + assert STATE_OFF == state.state # VacuumDevice should not support start and pause methods. self.hass.states.set(ENTITY_VACUUM_COMPLETE, STATE_ON) self.hass.block_till_done() - self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE)) + assert vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE) common.pause(self.hass, ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() - self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE)) + assert vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE) self.hass.states.set(ENTITY_VACUUM_COMPLETE, STATE_OFF) self.hass.block_till_done() - self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE)) + assert not vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE) common.start(self.hass, ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() - self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE)) + assert not vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE) # StateVacuumDevice does not support on/off common.turn_on(self.hass, entity_id=ENTITY_VACUUM_STATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertNotEqual(STATE_CLEANING, state.state) + assert STATE_CLEANING != state.state common.turn_off(self.hass, entity_id=ENTITY_VACUUM_STATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertNotEqual(STATE_RETURNING, state.state) + assert STATE_RETURNING != state.state common.toggle(self.hass, entity_id=ENTITY_VACUUM_STATE) self.hass.block_till_done() state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertNotEqual(STATE_CLEANING, state.state) + assert STATE_CLEANING != state.state def test_services(self): """Test vacuum services.""" @@ -294,14 +294,14 @@ class TestVacuumDemo(unittest.TestCase): params=params) self.hass.block_till_done() - self.assertEqual(1, len(send_command_calls)) + assert 1 == len(send_command_calls) call = send_command_calls[-1] - self.assertEqual(DOMAIN, call.domain) - self.assertEqual(SERVICE_SEND_COMMAND, call.service) - self.assertEqual(ENTITY_VACUUM_BASIC, call.data[ATTR_ENTITY_ID]) - self.assertEqual('test_command', call.data[ATTR_COMMAND]) - self.assertEqual(params, call.data[ATTR_PARAMS]) + assert DOMAIN == call.domain + assert SERVICE_SEND_COMMAND == call.service + assert ENTITY_VACUUM_BASIC == call.data[ATTR_ENTITY_ID] + assert 'test_command' == call.data[ATTR_COMMAND] + assert params == call.data[ATTR_PARAMS] # Test set fan speed set_fan_speed_calls = mock_service( @@ -311,13 +311,13 @@ class TestVacuumDemo(unittest.TestCase): self.hass, FAN_SPEEDS[0], entity_id=ENTITY_VACUUM_COMPLETE) self.hass.block_till_done() - self.assertEqual(1, len(set_fan_speed_calls)) + assert 1 == len(set_fan_speed_calls) call = set_fan_speed_calls[-1] - self.assertEqual(DOMAIN, call.domain) - self.assertEqual(SERVICE_SET_FAN_SPEED, call.service) - self.assertEqual(ENTITY_VACUUM_COMPLETE, call.data[ATTR_ENTITY_ID]) - self.assertEqual(FAN_SPEEDS[0], call.data[ATTR_FAN_SPEED]) + assert DOMAIN == call.domain + assert SERVICE_SET_FAN_SPEED == call.service + assert ENTITY_VACUUM_COMPLETE == call.data[ATTR_ENTITY_ID] + assert FAN_SPEEDS[0] == call.data[ATTR_FAN_SPEED] def test_set_fan_speed(self): """Test vacuum service to set the fan speed.""" @@ -336,20 +336,20 @@ class TestVacuumDemo(unittest.TestCase): new_state_complete = self.hass.states.get(ENTITY_VACUUM_COMPLETE) new_state_state = self.hass.states.get(ENTITY_VACUUM_STATE) - self.assertEqual(old_state_basic, new_state_basic) - self.assertNotIn(ATTR_FAN_SPEED, new_state_basic.attributes) + assert old_state_basic == new_state_basic + assert ATTR_FAN_SPEED not in new_state_basic.attributes - self.assertNotEqual(old_state_complete, new_state_complete) - self.assertEqual(FAN_SPEEDS[1], - old_state_complete.attributes[ATTR_FAN_SPEED]) - self.assertEqual(FAN_SPEEDS[0], - new_state_complete.attributes[ATTR_FAN_SPEED]) + assert old_state_complete != new_state_complete + assert FAN_SPEEDS[1] == \ + old_state_complete.attributes[ATTR_FAN_SPEED] + assert FAN_SPEEDS[0] == \ + new_state_complete.attributes[ATTR_FAN_SPEED] - self.assertNotEqual(old_state_state, new_state_state) - self.assertEqual(FAN_SPEEDS[1], - old_state_state.attributes[ATTR_FAN_SPEED]) - self.assertEqual(FAN_SPEEDS[0], - new_state_state.attributes[ATTR_FAN_SPEED]) + assert old_state_state != new_state_state + assert FAN_SPEEDS[1] == \ + old_state_state.attributes[ATTR_FAN_SPEED] + assert FAN_SPEEDS[0] == \ + new_state_state.attributes[ATTR_FAN_SPEED] def test_send_command(self): """Test vacuum service to send a command.""" @@ -366,8 +366,8 @@ class TestVacuumDemo(unittest.TestCase): new_state_basic = self.hass.states.get(ENTITY_VACUUM_BASIC) new_state_complete = self.hass.states.get(ENTITY_VACUUM_COMPLETE) - self.assertEqual(old_state_basic, new_state_basic) - self.assertNotEqual(old_state_complete, new_state_complete) - self.assertEqual(STATE_ON, new_state_complete.state) - self.assertEqual("Executing test_command({'p1': 3})", - new_state_complete.attributes[ATTR_STATUS]) + assert old_state_basic == new_state_basic + assert old_state_complete != new_state_complete + assert STATE_ON == new_state_complete.state + assert "Executing test_command({'p1': 3})" == \ + new_state_complete.attributes[ATTR_STATUS] diff --git a/tests/components/vacuum/test_dyson.py b/tests/components/vacuum/test_dyson.py index e9e6aaa1b..0bdaa619c 100644 --- a/tests/components/vacuum/test_dyson.py +++ b/tests/components/vacuum/test_dyson.py @@ -100,13 +100,13 @@ class DysonTest(unittest.TestCase): component.entity_id = "entity_id" component.schedule_update_ha_state = mock.Mock() component.on_message(mock.Mock()) - self.assertTrue(component.schedule_update_ha_state.called) + assert component.schedule_update_ha_state.called def test_should_poll(self): """Test polling is disable.""" device = _get_vacuum_device_cleaning() component = Dyson360EyeDevice(device) - self.assertFalse(component.should_poll) + assert not component.should_poll def test_properties(self): """Test component properties.""" @@ -116,45 +116,45 @@ class DysonTest(unittest.TestCase): component = Dyson360EyeDevice(device1) component2 = Dyson360EyeDevice(device2) component3 = Dyson360EyeDevice(device3) - self.assertEqual(component.name, "Device_Vacuum") - self.assertTrue(component.is_on) - self.assertEqual(component.status, "Cleaning") - self.assertEqual(component2.status, "Unknown") - self.assertEqual(component.battery_level, 85) - self.assertEqual(component.fan_speed, "Quiet") - self.assertEqual(component.fan_speed_list, ["Quiet", "Max"]) - self.assertEqual(component.device_state_attributes['position'], - '(0, 0)') - self.assertTrue(component.available) - self.assertEqual(component.supported_features, 255) - self.assertEqual(component.battery_icon, "mdi:battery-80") - self.assertEqual(component3.battery_icon, "mdi:battery-charging-40") + assert component.name == "Device_Vacuum" + assert component.is_on + assert component.status == "Cleaning" + assert component2.status == "Unknown" + assert component.battery_level == 85 + assert component.fan_speed == "Quiet" + assert component.fan_speed_list == ["Quiet", "Max"] + assert component.device_state_attributes['position'] == \ + '(0, 0)' + assert component.available + assert component.supported_features == 255 + assert component.battery_icon == "mdi:battery-80" + assert component3.battery_icon == "mdi:battery-charging-40" def test_turn_on(self): """Test turn on vacuum.""" device1 = _get_vacuum_device_charging() component1 = Dyson360EyeDevice(device1) component1.turn_on() - self.assertTrue(device1.start.called) + assert device1.start.called device2 = _get_vacuum_device_pause() component2 = Dyson360EyeDevice(device2) component2.turn_on() - self.assertTrue(device2.resume.called) + assert device2.resume.called def test_turn_off(self): """Test turn off vacuum.""" device1 = _get_vacuum_device_cleaning() component1 = Dyson360EyeDevice(device1) component1.turn_off() - self.assertTrue(device1.pause.called) + assert device1.pause.called def test_stop(self): """Test stop vacuum.""" device1 = _get_vacuum_device_cleaning() component1 = Dyson360EyeDevice(device1) component1.stop() - self.assertTrue(device1.pause.called) + assert device1.pause.called def test_set_fan_speed(self): """Test set fan speed vacuum.""" @@ -168,21 +168,21 @@ class DysonTest(unittest.TestCase): device1 = _get_vacuum_device_charging() component1 = Dyson360EyeDevice(device1) component1.start_pause() - self.assertTrue(device1.start.called) + assert device1.start.called device2 = _get_vacuum_device_pause() component2 = Dyson360EyeDevice(device2) component2.start_pause() - self.assertTrue(device2.resume.called) + assert device2.resume.called device3 = _get_vacuum_device_cleaning() component3 = Dyson360EyeDevice(device3) component3.start_pause() - self.assertTrue(device3.pause.called) + assert device3.pause.called def test_return_to_base(self): """Test return to base.""" device = _get_vacuum_device_pause() component = Dyson360EyeDevice(device) component.return_to_base() - self.assertTrue(device.abort.called) + assert device.abort.called diff --git a/tests/components/vacuum/test_mqtt.py b/tests/components/vacuum/test_mqtt.py index ddd4289c2..ba2c18668 100644 --- a/tests/components/vacuum/test_mqtt.py +++ b/tests/components/vacuum/test_mqtt.py @@ -51,25 +51,25 @@ class TestVacuumMQTT(unittest.TestCase): def test_default_supported_features(self): """Test that the correct supported features.""" - self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { + assert setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, - })) + }) entity = self.hass.states.get('vacuum.mqtttest') entity_features = \ entity.attributes.get(mqtt.CONF_SUPPORTED_FEATURES, 0) - self.assertListEqual(sorted(mqtt.services_to_strings(entity_features)), - sorted(['turn_on', 'turn_off', 'stop', - 'return_home', 'battery', 'status', - 'clean_spot'])) + assert sorted(mqtt.services_to_strings(entity_features)) == \ + sorted(['turn_on', 'turn_off', 'stop', + 'return_home', 'battery', 'status', + 'clean_spot']) def test_all_commands(self): """Test simple commands to the vacuum.""" self.default_config[mqtt.CONF_SUPPORTED_FEATURES] = \ mqtt.services_to_strings(mqtt.ALL_SERVICES) - self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { + assert setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, - })) + }) common.turn_on(self.hass, 'vacuum.mqtttest') self.hass.block_till_done() @@ -129,9 +129,9 @@ class TestVacuumMQTT(unittest.TestCase): self.default_config[mqtt.CONF_SUPPORTED_FEATURES] = \ mqtt.services_to_strings(mqtt.ALL_SERVICES) - self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { + assert setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, - })) + }) message = """{ "battery_level": 54, @@ -143,13 +143,11 @@ class TestVacuumMQTT(unittest.TestCase): fire_mqtt_message(self.hass, 'vacuum/state', message) self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') - self.assertEqual(STATE_ON, state.state) - self.assertEqual( - 'mdi:battery-50', + assert STATE_ON == state.state + assert 'mdi:battery-50' == \ state.attributes.get(ATTR_BATTERY_ICON) - ) - self.assertEqual(54, state.attributes.get(ATTR_BATTERY_LEVEL)) - self.assertEqual('max', state.attributes.get(ATTR_FAN_SPEED)) + assert 54 == state.attributes.get(ATTR_BATTERY_LEVEL) + assert 'max' == state.attributes.get(ATTR_FAN_SPEED) message = """{ "battery_level": 61, @@ -162,13 +160,11 @@ class TestVacuumMQTT(unittest.TestCase): fire_mqtt_message(self.hass, 'vacuum/state', message) self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') - self.assertEqual(STATE_OFF, state.state) - self.assertEqual( - 'mdi:battery-charging-60', + assert STATE_OFF == state.state + assert 'mdi:battery-charging-60' == \ state.attributes.get(ATTR_BATTERY_ICON) - ) - self.assertEqual(61, state.attributes.get(ATTR_BATTERY_LEVEL)) - self.assertEqual('min', state.attributes.get(ATTR_FAN_SPEED)) + assert 61 == state.attributes.get(ATTR_BATTERY_LEVEL) + assert 'min' == state.attributes.get(ATTR_FAN_SPEED) def test_battery_template(self): """Test that you can use non-default templates for battery_level.""" @@ -179,31 +175,31 @@ class TestVacuumMQTT(unittest.TestCase): mqtt.CONF_BATTERY_LEVEL_TEMPLATE: "{{ value }}" }) - self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { + assert setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, - })) + }) fire_mqtt_message(self.hass, 'retroroomba/battery_level', '54') self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') - self.assertEqual(54, state.attributes.get(ATTR_BATTERY_LEVEL)) - self.assertEqual(state.attributes.get(ATTR_BATTERY_ICON), - 'mdi:battery-50') + assert 54 == state.attributes.get(ATTR_BATTERY_LEVEL) + assert state.attributes.get(ATTR_BATTERY_ICON) == \ + 'mdi:battery-50' def test_status_invalid_json(self): """Test to make sure nothing breaks if the vacuum sends bad JSON.""" self.default_config[mqtt.CONF_SUPPORTED_FEATURES] = \ mqtt.services_to_strings(mqtt.ALL_SERVICES) - self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { + assert setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, - })) + }) fire_mqtt_message(self.hass, 'vacuum/state', '{"asdfasas false}') self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') - self.assertEqual(STATE_OFF, state.state) - self.assertEqual("Stopped", state.attributes.get(ATTR_STATUS)) + assert STATE_OFF == state.state + assert "Stopped" == state.attributes.get(ATTR_STATUS) def test_default_availability_payload(self): """Test availability by default payload with defined topic.""" @@ -211,24 +207,24 @@ class TestVacuumMQTT(unittest.TestCase): 'availability_topic': 'availability-topic' }) - self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { + assert setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, - })) + }) state = self.hass.states.get('vacuum.mqtttest') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'online') self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'offline') self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state def test_custom_availability_payload(self): """Test availability by custom payload with defined topic.""" @@ -238,21 +234,21 @@ class TestVacuumMQTT(unittest.TestCase): 'payload_not_available': 'nogood' }) - self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { + assert setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, - })) + }) state = self.hass.states.get('vacuum.mqtttest') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state fire_mqtt_message(self.hass, 'availability-topic', 'good') self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') - self.assertNotEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE != state.state fire_mqtt_message(self.hass, 'availability-topic', 'nogood') self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') - self.assertEqual(STATE_UNAVAILABLE, state.state) + assert STATE_UNAVAILABLE == state.state diff --git a/tests/components/water_heater/test_demo.py b/tests/components/water_heater/test_demo.py index 14fe57de9..66116db8c 100644 --- a/tests/components/water_heater/test_demo.py +++ b/tests/components/water_heater/test_demo.py @@ -22,10 +22,10 @@ class TestDemowater_heater(unittest.TestCase): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.units = IMPERIAL_SYSTEM - self.assertTrue(setup_component(self.hass, water_heater.DOMAIN, { + assert setup_component(self.hass, water_heater.DOMAIN, { 'water_heater': { 'platform': 'demo', - }})) + }}) def tearDown(self): # pylint: disable=invalid-name """Stop down everything that was started.""" @@ -34,32 +34,32 @@ class TestDemowater_heater(unittest.TestCase): def test_setup_params(self): """Test the initial parameters.""" state = self.hass.states.get(ENTITY_WATER_HEATER) - self.assertEqual(119, state.attributes.get('temperature')) - self.assertEqual('off', state.attributes.get('away_mode')) - self.assertEqual("eco", state.attributes.get('operation_mode')) + assert 119 == state.attributes.get('temperature') + assert 'off' == state.attributes.get('away_mode') + assert "eco" == state.attributes.get('operation_mode') def test_default_setup_params(self): """Test the setup with default parameters.""" state = self.hass.states.get(ENTITY_WATER_HEATER) - self.assertEqual(110, state.attributes.get('min_temp')) - self.assertEqual(140, state.attributes.get('max_temp')) + assert 110 == state.attributes.get('min_temp') + assert 140 == state.attributes.get('max_temp') def test_set_only_target_temp_bad_attr(self): """Test setting the target temperature without required attribute.""" state = self.hass.states.get(ENTITY_WATER_HEATER) - self.assertEqual(119, state.attributes.get('temperature')) + assert 119 == state.attributes.get('temperature') common.set_temperature(self.hass, None, ENTITY_WATER_HEATER) self.hass.block_till_done() - self.assertEqual(119, state.attributes.get('temperature')) + assert 119 == state.attributes.get('temperature') def test_set_only_target_temp(self): """Test the setting of the target temperature.""" state = self.hass.states.get(ENTITY_WATER_HEATER) - self.assertEqual(119, state.attributes.get('temperature')) + assert 119 == state.attributes.get('temperature') common.set_temperature(self.hass, 110, ENTITY_WATER_HEATER) self.hass.block_till_done() state = self.hass.states.get(ENTITY_WATER_HEATER) - self.assertEqual(110, state.attributes.get('temperature')) + assert 110 == state.attributes.get('temperature') def test_set_operation_bad_attr_and_state(self): """Test setting operation mode without required attribute. @@ -67,52 +67,52 @@ class TestDemowater_heater(unittest.TestCase): Also check the state. """ state = self.hass.states.get(ENTITY_WATER_HEATER) - self.assertEqual("eco", state.attributes.get('operation_mode')) - self.assertEqual("eco", state.state) + assert "eco" == state.attributes.get('operation_mode') + assert "eco" == state.state common.set_operation_mode(self.hass, None, ENTITY_WATER_HEATER) self.hass.block_till_done() state = self.hass.states.get(ENTITY_WATER_HEATER) - self.assertEqual("eco", state.attributes.get('operation_mode')) - self.assertEqual("eco", state.state) + assert "eco" == state.attributes.get('operation_mode') + assert "eco" == state.state def test_set_operation(self): """Test setting of new operation mode.""" state = self.hass.states.get(ENTITY_WATER_HEATER) - self.assertEqual("eco", state.attributes.get('operation_mode')) - self.assertEqual("eco", state.state) + assert "eco" == state.attributes.get('operation_mode') + assert "eco" == state.state common.set_operation_mode(self.hass, "electric", ENTITY_WATER_HEATER) self.hass.block_till_done() state = self.hass.states.get(ENTITY_WATER_HEATER) - self.assertEqual("electric", state.attributes.get('operation_mode')) - self.assertEqual("electric", state.state) + assert "electric" == state.attributes.get('operation_mode') + assert "electric" == state.state def test_set_away_mode_bad_attr(self): """Test setting the away mode without required attribute.""" state = self.hass.states.get(ENTITY_WATER_HEATER) - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') common.set_away_mode(self.hass, None, ENTITY_WATER_HEATER) self.hass.block_till_done() - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') def test_set_away_mode_on(self): """Test setting the away mode on/true.""" common.set_away_mode(self.hass, True, ENTITY_WATER_HEATER) self.hass.block_till_done() state = self.hass.states.get(ENTITY_WATER_HEATER) - self.assertEqual('on', state.attributes.get('away_mode')) + assert 'on' == state.attributes.get('away_mode') def test_set_away_mode_off(self): """Test setting the away mode off/false.""" common.set_away_mode(self.hass, False, ENTITY_WATER_HEATER_CELSIUS) self.hass.block_till_done() state = self.hass.states.get(ENTITY_WATER_HEATER_CELSIUS) - self.assertEqual('off', state.attributes.get('away_mode')) + assert 'off' == state.attributes.get('away_mode') def test_set_only_target_temp_with_convert(self): """Test the setting of the target temperature.""" state = self.hass.states.get(ENTITY_WATER_HEATER_CELSIUS) - self.assertEqual(113, state.attributes.get('temperature')) + assert 113 == state.attributes.get('temperature') common.set_temperature(self.hass, 114, ENTITY_WATER_HEATER_CELSIUS) self.hass.block_till_done() state = self.hass.states.get(ENTITY_WATER_HEATER_CELSIUS) - self.assertEqual(114, state.attributes.get('temperature')) + assert 114 == state.attributes.get('temperature') diff --git a/tests/components/weather/test_darksky.py b/tests/components/weather/test_darksky.py index 5423943e6..8530b2ff4 100644 --- a/tests/components/weather/test_darksky.py +++ b/tests/components/weather/test_darksky.py @@ -36,16 +36,16 @@ class TestDarkSky(unittest.TestCase): mock_req.get(re.compile(uri), text=load_fixture('darksky.json')) - self.assertTrue(setup_component(self.hass, weather.DOMAIN, { + assert setup_component(self.hass, weather.DOMAIN, { 'weather': { 'name': 'test', 'platform': 'darksky', 'api_key': 'foo', } - })) + }) - self.assertTrue(mock_get_forecast.called) - self.assertEqual(mock_get_forecast.call_count, 1) + assert mock_get_forecast.called + assert mock_get_forecast.call_count == 1 state = self.hass.states.get('weather.test') - self.assertEqual(state.state, 'sunny') + assert state.state == 'sunny' diff --git a/tests/components/weather/test_ipma.py b/tests/components/weather/test_ipma.py index d438e1185..c7c89ecdb 100644 --- a/tests/components/weather/test_ipma.py +++ b/tests/components/weather/test_ipma.py @@ -66,20 +66,20 @@ class TestIPMA(unittest.TestCase): @patch("pyipma.Station", new=MockStation) def test_setup(self, mock_pyipma): """Test for successfully setting up the IPMA platform.""" - self.assertTrue(setup_component(self.hass, weather.DOMAIN, { + assert setup_component(self.hass, weather.DOMAIN, { 'weather': { 'name': 'HomeTown', 'platform': 'ipma', } - })) + }) state = self.hass.states.get('weather.hometown') - self.assertEqual(state.state, 'rainy') + assert state.state == 'rainy' data = state.attributes - self.assertEqual(data.get(ATTR_WEATHER_TEMPERATURE), 18.0) - self.assertEqual(data.get(ATTR_WEATHER_HUMIDITY), 71) - self.assertEqual(data.get(ATTR_WEATHER_PRESSURE), 1000.0) - self.assertEqual(data.get(ATTR_WEATHER_WIND_SPEED), 3.94) - self.assertEqual(data.get(ATTR_WEATHER_WIND_BEARING), 'NW') - self.assertEqual(state.attributes.get('friendly_name'), 'HomeTown') + assert data.get(ATTR_WEATHER_TEMPERATURE) == 18.0 + assert data.get(ATTR_WEATHER_HUMIDITY) == 71 + assert data.get(ATTR_WEATHER_PRESSURE) == 1000.0 + assert data.get(ATTR_WEATHER_WIND_SPEED) == 3.94 + assert data.get(ATTR_WEATHER_WIND_BEARING) == 'NW' + assert state.attributes.get('friendly_name') == 'HomeTown' diff --git a/tests/components/weather/test_weather.py b/tests/components/weather/test_weather.py index 42b1dacc5..ba8caee04 100644 --- a/tests/components/weather/test_weather.py +++ b/tests/components/weather/test_weather.py @@ -20,11 +20,11 @@ class TestWeather(unittest.TestCase): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.units = METRIC_SYSTEM - self.assertTrue(setup_component(self.hass, weather.DOMAIN, { + assert setup_component(self.hass, weather.DOMAIN, { 'weather': { 'platform': 'demo', } - })) + }) def tearDown(self): """Stop down everything that was started.""" diff --git a/tests/components/weather/test_yweather.py b/tests/components/weather/test_yweather.py index a808eb4e4..6738d1cd9 100644 --- a/tests/components/weather/test_yweather.py +++ b/tests/components/weather/test_yweather.py @@ -97,12 +97,11 @@ class TestWeather(unittest.TestCase): @patch('yahooweather.YahooWeather', new=YahooWeatherMock) def test_setup(self, mock_yahooweather): """Test for typical weather data attributes.""" - self.assertTrue( - setup_component(self.hass, 'weather', { + assert setup_component(self.hass, 'weather', { 'weather': { 'platform': 'yweather', } - })) + }) state = self.hass.states.get('weather.yweather') assert state is not None @@ -110,12 +109,12 @@ class TestWeather(unittest.TestCase): assert state.state == 'cloudy' data = state.attributes - self.assertEqual(data.get(ATTR_WEATHER_TEMPERATURE), 18.0) - self.assertEqual(data.get(ATTR_WEATHER_HUMIDITY), 71) - self.assertEqual(data.get(ATTR_WEATHER_PRESSURE), 1000.0) - self.assertEqual(data.get(ATTR_WEATHER_WIND_SPEED), 3.94) - self.assertEqual(data.get(ATTR_WEATHER_WIND_BEARING), 0) - self.assertEqual(state.attributes.get('friendly_name'), 'Yweather') + assert data.get(ATTR_WEATHER_TEMPERATURE) == 18.0 + assert data.get(ATTR_WEATHER_HUMIDITY) == 71 + assert data.get(ATTR_WEATHER_PRESSURE) == 1000.0 + assert data.get(ATTR_WEATHER_WIND_SPEED) == 3.94 + assert data.get(ATTR_WEATHER_WIND_BEARING) == 0 + assert state.attributes.get('friendly_name') == 'Yweather' @MockDependency('yahooweather') @patch('yahooweather._yql_query', new=_yql_queryMock) @@ -123,13 +122,12 @@ class TestWeather(unittest.TestCase): @patch('yahooweather.YahooWeather', new=YahooWeatherMock) def test_setup_no_data(self, mock_yahooweather): """Test for note receiving data.""" - self.assertTrue( - setup_component(self.hass, 'weather', { + assert setup_component(self.hass, 'weather', { 'weather': { 'platform': 'yweather', 'woeid': '12345', } - })) + }) state = self.hass.states.get('weather.yweather') assert state is not None @@ -140,13 +138,12 @@ class TestWeather(unittest.TestCase): @patch('yahooweather.YahooWeather', new=YahooWeatherMock) def test_setup_bad_data(self, mock_yahooweather): """Test for bad forecast data.""" - self.assertTrue( - setup_component(self.hass, 'weather', { + assert setup_component(self.hass, 'weather', { 'weather': { 'platform': 'yweather', 'woeid': '123123', } - })) + }) state = self.hass.states.get('weather.yweather') assert state is None @@ -157,13 +154,12 @@ class TestWeather(unittest.TestCase): @patch('yahooweather.YahooWeather', new=YahooWeatherMock) def test_setup_condition_error(self, mock_yahooweather): """Test for bad forecast data.""" - self.assertTrue( - setup_component(self.hass, 'weather', { + assert setup_component(self.hass, 'weather', { 'weather': { 'platform': 'yweather', 'woeid': '111', } - })) + }) state = self.hass.states.get('weather.yweather') assert state is None diff --git a/tests/components/zwave/test_init.py b/tests/components/zwave/test_init.py index b06dfb683..eb28dcc02 100644 --- a/tests/components/zwave/test_init.py +++ b/tests/components/zwave/test_init.py @@ -566,10 +566,8 @@ class TestZWaveDeviceEntityValues(unittest.TestCase): assert values.primary is self.primary assert len(list(values)) == 3 - self.assertEqual(sorted(list(values), - key=lambda a: id(a)), - sorted([self.primary, None, None], - key=lambda a: id(a))) + assert sorted(list(values), key=lambda a: id(a)) == \ + sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) @@ -577,10 +575,8 @@ class TestZWaveDeviceEntityValues(unittest.TestCase): assert values.secondary is self.secondary assert len(list(values)) == 3 - self.assertEqual(sorted(list(values), - key=lambda a: id(a)), - sorted([self.primary, self.secondary, None], - key=lambda a: id(a))) + assert sorted(list(values), key=lambda a: id(a)) == \ + sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 @@ -599,10 +595,9 @@ class TestZWaveDeviceEntityValues(unittest.TestCase): assert values.optional is self.optional assert len(list(values)) == 3 - self.assertEqual(sorted(list(values), - key=lambda a: id(a)), - sorted([self.primary, self.secondary, self.optional], - key=lambda a: id(a))) + assert sorted(list(values), key=lambda a: id(a)) == \ + sorted([self.primary, self.secondary, self.optional], + key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called @@ -641,10 +636,9 @@ class TestZWaveDeviceEntityValues(unittest.TestCase): assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 - self.assertEqual(sorted(list(values), - key=lambda a: id(a)), - sorted([self.primary, self.secondary, self.optional], - key=lambda a: id(a))) + assert sorted(list(values), key=lambda a: id(a)) == \ + sorted([self.primary, self.secondary, self.optional], + key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 @@ -869,8 +863,7 @@ class TestZwave(unittest.TestCase): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) - self.assertIsInstance( - conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) + assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): @@ -1228,7 +1221,7 @@ class TestZWaveServices(unittest.TestCase): }) self.hass.block_till_done() - self.assertIn("FOUND NODE ", mock_logger.output[1]) + assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" @@ -1385,9 +1378,9 @@ class TestZWaveServices(unittest.TestCase): assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 - self.assertEqual(sorted([node.refresh_value.mock_calls[0][1][0], - node.refresh_value.mock_calls[1][1][0]]), - sorted([value.value_id, power_value.value_id])) + assert sorted([node.refresh_value.mock_calls[0][1][0], + node.refresh_value.mock_calls[1][1][0]]) == \ + sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" diff --git a/tests/components/zwave/test_node_entity.py b/tests/components/zwave/test_node_entity.py index b91245d5a..034360c6b 100644 --- a/tests/components/zwave/test_node_entity.py +++ b/tests/components/zwave/test_node_entity.py @@ -203,7 +203,7 @@ class TestZWaveNodeEntity(unittest.TestCase): with patch.object(self.entity, 'maybe_schedule_update') as mock: node = mock_zwave.MockNode(node_id=1024) mock_zwave.node_changed(node) - self.assertFalse(mock.called) + assert not mock.called def test_network_node_changed_from_notification(self): """Test for network_node_changed.""" @@ -215,17 +215,17 @@ class TestZWaveNodeEntity(unittest.TestCase): """Test for network_node_changed.""" with patch.object(self.entity, 'maybe_schedule_update') as mock: mock_zwave.notification(node_id=1024) - self.assertFalse(mock.called) + assert not mock.called def test_node_changed(self): """Test node_changed function.""" self.maxDiff = None - self.assertEqual( - {'node_id': self.node.node_id, - 'node_name': 'Mock Node', - 'manufacturer_name': 'Test Manufacturer', - 'product_name': 'Test Product'}, - self.entity.device_state_attributes) + assert { + 'node_id': self.node.node_id, + 'node_name': 'Mock Node', + 'manufacturer_name': 'Test Manufacturer', + 'product_name': 'Test Product' + } == self.entity.device_state_attributes self.node.get_values.return_value = { 1: mock_zwave.MockValue(data=1800) @@ -278,87 +278,86 @@ class TestZWaveNodeEntity(unittest.TestCase): "averageResponseRTT": 2443, "receivedTS": "2017-03-27 15:38:19:298 "} self.entity.node_changed() - self.assertEqual( - {'node_id': self.node.node_id, - 'node_name': 'Mock Node', - 'manufacturer_name': 'Test Manufacturer', - 'product_name': 'Test Product', - 'query_stage': 'Dynamic', - 'is_awake': True, - 'is_ready': False, - 'is_failed': False, - 'is_info_received': True, - 'max_baud_rate': 40000, - 'is_zwave_plus': False, - 'battery_level': 42, - 'wake_up_interval': 1800, - 'averageRequestRTT': 2462, - 'averageResponseRTT': 2443, - 'lastRequestRTT': 1591, - 'lastResponseRTT': 3679, - 'receivedCnt': 4, - 'receivedDups': 1, - 'receivedTS': '2017-03-27 15:38:19:298 ', - 'receivedUnsolicited': 0, - 'retries': 0, - 'sentCnt': 7, - 'sentFailed': 1, - 'sentTS': '2017-03-27 15:38:15:620 '}, - self.entity.device_state_attributes) + assert { + 'node_id': self.node.node_id, + 'node_name': 'Mock Node', + 'manufacturer_name': 'Test Manufacturer', + 'product_name': 'Test Product', + 'query_stage': 'Dynamic', + 'is_awake': True, + 'is_ready': False, + 'is_failed': False, + 'is_info_received': True, + 'max_baud_rate': 40000, + 'is_zwave_plus': False, + 'battery_level': 42, + 'wake_up_interval': 1800, + 'averageRequestRTT': 2462, + 'averageResponseRTT': 2443, + 'lastRequestRTT': 1591, + 'lastResponseRTT': 3679, + 'receivedCnt': 4, + 'receivedDups': 1, + 'receivedTS': '2017-03-27 15:38:19:298 ', + 'receivedUnsolicited': 0, + 'retries': 0, + 'sentCnt': 7, + 'sentFailed': 1, + 'sentTS': '2017-03-27 15:38:15:620 ' + } == self.entity.device_state_attributes self.node.can_wake_up_value = False self.entity.node_changed() - self.assertNotIn( - 'wake_up_interval', self.entity.device_state_attributes) + assert 'wake_up_interval' not in self.entity.device_state_attributes def test_name(self): """Test name property.""" - self.assertEqual('Mock Node', self.entity.name) + assert 'Mock Node' == self.entity.name def test_state_before_update(self): """Test state before update was called.""" - self.assertIsNone(self.entity.state) + assert self.entity.state is None def test_state_not_ready(self): """Test state property.""" self.node.is_ready = False self.entity.node_changed() - self.assertEqual('initializing', self.entity.state) + assert 'initializing' == self.entity.state self.node.is_failed = True self.node.query_stage = 'Complete' self.entity.node_changed() - self.assertEqual('dead', self.entity.state) + assert 'dead' == self.entity.state self.node.is_failed = False self.node.is_awake = False self.entity.node_changed() - self.assertEqual('sleeping', self.entity.state) + assert 'sleeping' == self.entity.state def test_state_ready(self): """Test state property.""" self.node.query_stage = 'Complete' self.node.is_ready = True self.entity.node_changed() - self.assertEqual('ready', self.entity.state) + assert 'ready' == self.entity.state self.node.is_failed = True self.entity.node_changed() - self.assertEqual('dead', self.entity.state) + assert 'dead' == self.entity.state self.node.is_failed = False self.node.is_awake = False self.entity.node_changed() - self.assertEqual('sleeping', self.entity.state) + assert 'sleeping' == self.entity.state def test_not_polled(self): """Test should_poll property.""" - self.assertFalse(self.entity.should_poll) + assert not self.entity.should_poll def test_unique_id(self): """Test unique_id.""" - self.assertEqual('node-567', self.entity.unique_id) + assert 'node-567' == self.entity.unique_id def test_unique_id_missing_data(self): """Test unique_id.""" @@ -366,4 +365,4 @@ class TestZWaveNodeEntity(unittest.TestCase): self.node.name = None entity = node_entity.ZWaveNodeEntity(self.node, self.zwave_network) - self.assertIsNone(entity.unique_id) + assert entity.unique_id is None diff --git a/tests/helpers/test_event.py b/tests/helpers/test_event.py index cb5866983..dd5744bbb 100644 --- a/tests/helpers/test_event.py +++ b/tests/helpers/test_event.py @@ -59,23 +59,23 @@ class TestEventHelpers(unittest.TestCase): self._send_time_changed(before_birthday) self.hass.block_till_done() - self.assertEqual(0, len(runs)) + assert 0 == len(runs) self._send_time_changed(birthday_paulus) self.hass.block_till_done() - self.assertEqual(1, len(runs)) + assert 1 == len(runs) # A point in time tracker will only fire once, this should do nothing self._send_time_changed(birthday_paulus) self.hass.block_till_done() - self.assertEqual(1, len(runs)) + assert 1 == len(runs) track_point_in_time( self.hass, callback(lambda x: runs.append(1)), birthday_paulus) self._send_time_changed(after_birthday) self.hass.block_till_done() - self.assertEqual(2, len(runs)) + assert 2 == len(runs) unsub = track_point_in_time( self.hass, callback(lambda x: runs.append(1)), birthday_paulus) @@ -83,7 +83,7 @@ class TestEventHelpers(unittest.TestCase): self._send_time_changed(after_birthday) self.hass.block_till_done() - self.assertEqual(2, len(runs)) + assert 2 == len(runs) def test_track_state_change(self): """Test track_state_change.""" @@ -113,56 +113,56 @@ class TestEventHelpers(unittest.TestCase): # Adding state to state machine self.hass.states.set("light.Bowl", "on") self.hass.block_till_done() - self.assertEqual(0, len(specific_runs)) - self.assertEqual(1, len(wildcard_runs)) - self.assertEqual(1, len(wildercard_runs)) - self.assertIsNone(wildcard_runs[-1][0]) - self.assertIsNotNone(wildcard_runs[-1][1]) + assert 0 == len(specific_runs) + assert 1 == len(wildcard_runs) + assert 1 == len(wildercard_runs) + assert wildcard_runs[-1][0] is None + assert wildcard_runs[-1][1] is not None # Set same state should not trigger a state change/listener self.hass.states.set('light.Bowl', 'on') self.hass.block_till_done() - self.assertEqual(0, len(specific_runs)) - self.assertEqual(1, len(wildcard_runs)) - self.assertEqual(1, len(wildercard_runs)) + assert 0 == len(specific_runs) + assert 1 == len(wildcard_runs) + assert 1 == len(wildercard_runs) # State change off -> on self.hass.states.set('light.Bowl', 'off') self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) - self.assertEqual(2, len(wildcard_runs)) - self.assertEqual(2, len(wildercard_runs)) + assert 1 == len(specific_runs) + assert 2 == len(wildcard_runs) + assert 2 == len(wildercard_runs) # State change off -> off self.hass.states.set('light.Bowl', 'off', {"some_attr": 1}) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) - self.assertEqual(3, len(wildcard_runs)) - self.assertEqual(3, len(wildercard_runs)) + assert 1 == len(specific_runs) + assert 3 == len(wildcard_runs) + assert 3 == len(wildercard_runs) # State change off -> on self.hass.states.set('light.Bowl', 'on') self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) - self.assertEqual(4, len(wildcard_runs)) - self.assertEqual(4, len(wildercard_runs)) + assert 1 == len(specific_runs) + assert 4 == len(wildcard_runs) + assert 4 == len(wildercard_runs) self.hass.states.remove('light.bowl') self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) - self.assertEqual(5, len(wildcard_runs)) - self.assertEqual(5, len(wildercard_runs)) - self.assertIsNotNone(wildcard_runs[-1][0]) - self.assertIsNone(wildcard_runs[-1][1]) - self.assertIsNotNone(wildercard_runs[-1][0]) - self.assertIsNone(wildercard_runs[-1][1]) + assert 1 == len(specific_runs) + assert 5 == len(wildcard_runs) + assert 5 == len(wildercard_runs) + assert wildcard_runs[-1][0] is not None + assert wildcard_runs[-1][1] is None + assert wildercard_runs[-1][0] is not None + assert wildercard_runs[-1][1] is None # Set state for different entity id self.hass.states.set('switch.kitchen', 'on') self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) - self.assertEqual(5, len(wildcard_runs)) - self.assertEqual(6, len(wildercard_runs)) + assert 1 == len(specific_runs) + assert 5 == len(wildcard_runs) + assert 6 == len(wildercard_runs) def test_track_template(self): """Test tracking template.""" @@ -203,37 +203,37 @@ class TestEventHelpers(unittest.TestCase): self.hass.states.set('switch.test', 'on') self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) - self.assertEqual(1, len(wildcard_runs)) - self.assertEqual(1, len(wildercard_runs)) + assert 1 == len(specific_runs) + assert 1 == len(wildcard_runs) + assert 1 == len(wildercard_runs) self.hass.states.set('switch.test', 'on') self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) - self.assertEqual(1, len(wildcard_runs)) - self.assertEqual(1, len(wildercard_runs)) + assert 1 == len(specific_runs) + assert 1 == len(wildcard_runs) + assert 1 == len(wildercard_runs) self.hass.states.set('switch.test', 'off') self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) - self.assertEqual(1, len(wildcard_runs)) - self.assertEqual(1, len(wildercard_runs)) + assert 1 == len(specific_runs) + assert 1 == len(wildcard_runs) + assert 1 == len(wildercard_runs) self.hass.states.set('switch.test', 'off') self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) - self.assertEqual(1, len(wildcard_runs)) - self.assertEqual(1, len(wildercard_runs)) + assert 1 == len(specific_runs) + assert 1 == len(wildcard_runs) + assert 1 == len(wildercard_runs) self.hass.states.set('switch.test', 'on') self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) - self.assertEqual(2, len(wildcard_runs)) - self.assertEqual(2, len(wildercard_runs)) + assert 2 == len(specific_runs) + assert 2 == len(wildcard_runs) + assert 2 == len(wildercard_runs) def test_track_same_state_simple_trigger(self): """Test track_same_change with trigger simple.""" @@ -270,17 +270,17 @@ class TestEventHelpers(unittest.TestCase): # Adding state to state machine self.hass.states.set("light.Bowl", "on") self.hass.block_till_done() - self.assertEqual(0, len(thread_runs)) - self.assertEqual(0, len(callback_runs)) - self.assertEqual(0, len(coroutine_runs)) + assert 0 == len(thread_runs) + assert 0 == len(callback_runs) + assert 0 == len(coroutine_runs) # change time to track and see if they trigger future = dt_util.utcnow() + period fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(1, len(thread_runs)) - self.assertEqual(1, len(callback_runs)) - self.assertEqual(1, len(coroutine_runs)) + assert 1 == len(thread_runs) + assert 1 == len(callback_runs) + assert 1 == len(coroutine_runs) def test_track_same_state_simple_no_trigger(self): """Test track_same_change with no trigger.""" @@ -299,18 +299,18 @@ class TestEventHelpers(unittest.TestCase): # Adding state to state machine self.hass.states.set("light.Bowl", "on") self.hass.block_till_done() - self.assertEqual(0, len(callback_runs)) + assert 0 == len(callback_runs) # Change state on state machine self.hass.states.set("light.Bowl", "off") self.hass.block_till_done() - self.assertEqual(0, len(callback_runs)) + assert 0 == len(callback_runs) # change time to track and see if they trigger future = dt_util.utcnow() + period fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(0, len(callback_runs)) + assert 0 == len(callback_runs) def test_track_same_state_simple_trigger_check_funct(self): """Test track_same_change with trigger and check funct.""" @@ -334,15 +334,15 @@ class TestEventHelpers(unittest.TestCase): # Adding state to state machine self.hass.states.set("light.Bowl", "on") self.hass.block_till_done() - self.assertEqual(0, len(callback_runs)) - self.assertEqual('on', check_func[-1][2].state) - self.assertEqual('light.bowl', check_func[-1][0]) + assert 0 == len(callback_runs) + assert 'on' == check_func[-1][2].state + assert 'light.bowl' == check_func[-1][0] # change time to track and see if they trigger future = dt_util.utcnow() + period fire_time_changed(self.hass, future) self.hass.block_till_done() - self.assertEqual(1, len(callback_runs)) + assert 1 == len(callback_runs) def test_track_time_interval(self): """Test tracking time interval.""" @@ -356,21 +356,21 @@ class TestEventHelpers(unittest.TestCase): self._send_time_changed(utc_now + timedelta(seconds=5)) self.hass.block_till_done() - self.assertEqual(0, len(specific_runs)) + assert 0 == len(specific_runs) self._send_time_changed(utc_now + timedelta(seconds=13)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) self._send_time_changed(utc_now + timedelta(minutes=20)) self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) + assert 2 == len(specific_runs) unsub() self._send_time_changed(utc_now + timedelta(seconds=30)) self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) + assert 2 == len(specific_runs) def test_track_sunrise(self): """Test track the sunrise.""" @@ -410,26 +410,26 @@ class TestEventHelpers(unittest.TestCase): # run tests self._send_time_changed(next_rising - offset) self.hass.block_till_done() - self.assertEqual(0, len(runs)) - self.assertEqual(0, len(offset_runs)) + assert 0 == len(runs) + assert 0 == len(offset_runs) self._send_time_changed(next_rising) self.hass.block_till_done() - self.assertEqual(1, len(runs)) - self.assertEqual(0, len(offset_runs)) + assert 1 == len(runs) + assert 0 == len(offset_runs) self._send_time_changed(next_rising + offset) self.hass.block_till_done() - self.assertEqual(1, len(runs)) - self.assertEqual(1, len(offset_runs)) + assert 1 == len(runs) + assert 1 == len(offset_runs) unsub() unsub2() self._send_time_changed(next_rising + offset) self.hass.block_till_done() - self.assertEqual(1, len(runs)) - self.assertEqual(1, len(offset_runs)) + assert 1 == len(runs) + assert 1 == len(offset_runs) def test_track_sunset(self): """Test track the sunset.""" @@ -469,26 +469,26 @@ class TestEventHelpers(unittest.TestCase): # Run tests self._send_time_changed(next_setting - offset) self.hass.block_till_done() - self.assertEqual(0, len(runs)) - self.assertEqual(0, len(offset_runs)) + assert 0 == len(runs) + assert 0 == len(offset_runs) self._send_time_changed(next_setting) self.hass.block_till_done() - self.assertEqual(1, len(runs)) - self.assertEqual(0, len(offset_runs)) + assert 1 == len(runs) + assert 0 == len(offset_runs) self._send_time_changed(next_setting + offset) self.hass.block_till_done() - self.assertEqual(1, len(runs)) - self.assertEqual(1, len(offset_runs)) + assert 1 == len(runs) + assert 1 == len(offset_runs) unsub() unsub2() self._send_time_changed(next_setting + offset) self.hass.block_till_done() - self.assertEqual(1, len(runs)) - self.assertEqual(1, len(offset_runs)) + assert 1 == len(runs) + assert 1 == len(offset_runs) def _send_time_changed(self, now): """Send a time changed event.""" @@ -524,26 +524,26 @@ class TestTrackTimeChange(unittest.TestCase): self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) - self.assertEqual(1, len(wildcard_runs)) + assert 1 == len(specific_runs) + assert 1 == len(wildcard_runs) self._send_time_changed(datetime(2014, 5, 24, 12, 0, 15)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) - self.assertEqual(2, len(wildcard_runs)) + assert 1 == len(specific_runs) + assert 2 == len(wildcard_runs) self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30)) self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) - self.assertEqual(3, len(wildcard_runs)) + assert 2 == len(specific_runs) + assert 3 == len(wildcard_runs) unsub() unsub_utc() self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30)) self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) - self.assertEqual(3, len(wildcard_runs)) + assert 2 == len(specific_runs) + assert 3 == len(wildcard_runs) def test_periodic_task_minute(self): """Test periodic tasks per minute.""" @@ -555,21 +555,21 @@ class TestTrackTimeChange(unittest.TestCase): self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 24, 12, 3, 0)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 24, 12, 5, 0)) self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) + assert 2 == len(specific_runs) unsub() self._send_time_changed(datetime(2014, 5, 24, 12, 5, 0)) self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) + assert 2 == len(specific_runs) def test_periodic_task_hour(self): """Test periodic tasks per hour.""" @@ -581,29 +581,29 @@ class TestTrackTimeChange(unittest.TestCase): self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 24, 23, 0, 0)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 25, 0, 0, 0)) self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) + assert 2 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 25, 1, 0, 0)) self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) + assert 2 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0)) self.hass.block_till_done() - self.assertEqual(3, len(specific_runs)) + assert 3 == len(specific_runs) unsub() self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0)) self.hass.block_till_done() - self.assertEqual(3, len(specific_runs)) + assert 3 == len(specific_runs) def test_periodic_task_wrong_input(self): """Test periodic tasks with wrong input.""" @@ -615,7 +615,7 @@ class TestTrackTimeChange(unittest.TestCase): self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0)) self.hass.block_till_done() - self.assertEqual(0, len(specific_runs)) + assert 0 == len(specific_runs) def test_periodic_task_clock_rollback(self): """Test periodic tasks with the time rolling backwards.""" @@ -627,29 +627,29 @@ class TestTrackTimeChange(unittest.TestCase): self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 24, 23, 0, 0)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0)) self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) + assert 2 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 24, 0, 0, 0)) self.hass.block_till_done() - self.assertEqual(3, len(specific_runs)) + assert 3 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0)) self.hass.block_till_done() - self.assertEqual(4, len(specific_runs)) + assert 4 == len(specific_runs) unsub() self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0)) self.hass.block_till_done() - self.assertEqual(4, len(specific_runs)) + assert 4 == len(specific_runs) def test_periodic_task_duplicate_time(self): """Test periodic tasks not triggering on duplicate time.""" @@ -661,15 +661,15 @@ class TestTrackTimeChange(unittest.TestCase): self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) self._send_time_changed(datetime(2014, 5, 25, 0, 0, 0)) self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) + assert 2 == len(specific_runs) unsub() @@ -686,22 +686,22 @@ class TestTrackTimeChange(unittest.TestCase): self._send_time_changed( tz.localize(datetime(2018, 3, 25, 1, 50, 0))) self.hass.block_till_done() - self.assertEqual(0, len(specific_runs)) + assert 0 == len(specific_runs) self._send_time_changed( tz.localize(datetime(2018, 3, 25, 3, 50, 0))) self.hass.block_till_done() - self.assertEqual(0, len(specific_runs)) + assert 0 == len(specific_runs) self._send_time_changed( tz.localize(datetime(2018, 3, 26, 1, 50, 0))) self.hass.block_till_done() - self.assertEqual(0, len(specific_runs)) + assert 0 == len(specific_runs) self._send_time_changed( tz.localize(datetime(2018, 3, 26, 2, 50, 0))) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) unsub() @@ -718,22 +718,22 @@ class TestTrackTimeChange(unittest.TestCase): self._send_time_changed( tz.localize(datetime(2018, 10, 28, 2, 5, 0), is_dst=False)) self.hass.block_till_done() - self.assertEqual(0, len(specific_runs)) + assert 0 == len(specific_runs) self._send_time_changed( tz.localize(datetime(2018, 10, 28, 2, 55, 0), is_dst=False)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) self._send_time_changed( tz.localize(datetime(2018, 10, 28, 2, 5, 0), is_dst=True)) self.hass.block_till_done() - self.assertEqual(1, len(specific_runs)) + assert 1 == len(specific_runs) self._send_time_changed( tz.localize(datetime(2018, 10, 28, 2, 55, 0), is_dst=True)) self.hass.block_till_done() - self.assertEqual(2, len(specific_runs)) + assert 2 == len(specific_runs) unsub() diff --git a/tests/helpers/test_icon.py b/tests/helpers/test_icon.py index 29507b25c..417dded79 100644 --- a/tests/helpers/test_icon.py +++ b/tests/helpers/test_icon.py @@ -9,20 +9,20 @@ class TestIconUtil(unittest.TestCase): """Test icon generator for battery sensor.""" from homeassistant.helpers.icon import icon_for_battery_level - self.assertEqual('mdi:battery-unknown', - icon_for_battery_level(None, True)) - self.assertEqual('mdi:battery-unknown', - icon_for_battery_level(None, False)) + assert 'mdi:battery-unknown' == \ + icon_for_battery_level(None, True) + assert 'mdi:battery-unknown' == \ + icon_for_battery_level(None, False) - self.assertEqual('mdi:battery-outline', - icon_for_battery_level(5, True)) - self.assertEqual('mdi:battery-alert', - icon_for_battery_level(5, False)) + assert 'mdi:battery-outline' == \ + icon_for_battery_level(5, True) + assert 'mdi:battery-alert' == \ + icon_for_battery_level(5, False) - self.assertEqual('mdi:battery-charging-100', - icon_for_battery_level(100, True)) - self.assertEqual('mdi:battery', - icon_for_battery_level(100, False)) + assert 'mdi:battery-charging-100' == \ + icon_for_battery_level(100, True) + assert 'mdi:battery' == \ + icon_for_battery_level(100, False) iconbase = 'mdi:battery' for level in range(0, 100, 5): @@ -47,7 +47,7 @@ class TestIconUtil(unittest.TestCase): postfix = '-alert' else: postfix = '' - self.assertEqual(iconbase + postfix, - icon_for_battery_level(level, False)) - self.assertEqual(iconbase + postfix_charging, - icon_for_battery_level(level, True)) + assert iconbase + postfix == \ + icon_for_battery_level(level, False) + assert iconbase + postfix_charging == \ + icon_for_battery_level(level, True) diff --git a/tests/helpers/test_init.py b/tests/helpers/test_init.py index f702c1a5d..6af28e686 100644 --- a/tests/helpers/test_init.py +++ b/tests/helpers/test_init.py @@ -31,8 +31,8 @@ class TestHelpers(unittest.TestCase): 'zone 100': None, } - self.assertEqual(set(['zone', 'zone Hallo', 'zone 100']), - set(helpers.extract_domain_configs(config, 'zone'))) + assert set(['zone', 'zone Hallo', 'zone 100']) == \ + set(helpers.extract_domain_configs(config, 'zone')) def test_config_per_platform(self): """Test config per platform method.""" diff --git a/tests/helpers/test_intent.py b/tests/helpers/test_intent.py index 707129ae5..1a5b63fba 100644 --- a/tests/helpers/test_intent.py +++ b/tests/helpers/test_intent.py @@ -5,6 +5,7 @@ import voluptuous as vol from homeassistant.core import State from homeassistant.helpers import (intent, config_validation as cv) +import pytest class MockIntentHandler(intent.IntentHandler): @@ -33,12 +34,12 @@ class TestIntentHandler(unittest.TestCase): vol.Required('name'): cv.string, }) - self.assertRaises(vol.error.MultipleInvalid, - handler1.async_validate_slots, {}) - self.assertRaises(vol.error.MultipleInvalid, - handler1.async_validate_slots, {'name': 1}) - self.assertRaises(vol.error.MultipleInvalid, - handler1.async_validate_slots, {'name': 'kitchen'}) + with pytest.raises(vol.error.MultipleInvalid): + handler1.async_validate_slots({}) + with pytest.raises(vol.error.MultipleInvalid): + handler1.async_validate_slots({'name': 1}) + with pytest.raises(vol.error.MultipleInvalid): + handler1.async_validate_slots({'name': 'kitchen'}) handler1.async_validate_slots({'name': {'value': 'kitchen'}}) handler1.async_validate_slots({ 'name': {'value': 'kitchen'}, diff --git a/tests/helpers/test_location.py b/tests/helpers/test_location.py index 22f69c183..5ff7abdbc 100644 --- a/tests/helpers/test_location.py +++ b/tests/helpers/test_location.py @@ -12,7 +12,7 @@ class TestHelpersLocation(unittest.TestCase): def test_has_location_with_invalid_states(self): """Set up the tests.""" for state in (None, 1, "hello", object): - self.assertFalse(location.has_location(state)) + assert not location.has_location(state) def test_has_location_with_states_with_invalid_locations(self): """Set up the tests.""" @@ -20,7 +20,7 @@ class TestHelpersLocation(unittest.TestCase): ATTR_LATITUDE: 'no number', ATTR_LONGITUDE: 123.12 }) - self.assertFalse(location.has_location(state)) + assert not location.has_location(state) def test_has_location_with_states_with_valid_location(self): """Set up the tests.""" @@ -28,7 +28,7 @@ class TestHelpersLocation(unittest.TestCase): ATTR_LATITUDE: 123.12, ATTR_LONGITUDE: 123.12 }) - self.assertTrue(location.has_location(state)) + assert location.has_location(state) def test_closest_with_no_states_with_location(self): """Set up the tests.""" @@ -41,8 +41,8 @@ class TestHelpersLocation(unittest.TestCase): ATTR_LONGITUDE: 123.45, }) - self.assertIsNone( - location.closest(123.45, 123.45, [state, state2, state3])) + assert \ + location.closest(123.45, 123.45, [state, state2, state3]) is None def test_closest_returns_closest(self): """Test .""" @@ -55,5 +55,4 @@ class TestHelpersLocation(unittest.TestCase): ATTR_LONGITUDE: 125.45, }) - self.assertEqual( - state, location.closest(123.45, 123.45, [state, state2])) + assert state == location.closest(123.45, 123.45, [state, state2]) diff --git a/tests/helpers/test_service.py b/tests/helpers/test_service.py index 529804bd3..71775574c 100644 --- a/tests/helpers/test_service.py +++ b/tests/helpers/test_service.py @@ -45,10 +45,10 @@ class TestServiceHelpers(unittest.TestCase): service.call_from_config(self.hass, config) self.hass.block_till_done() - self.assertEqual('goodbye', self.calls[0].data['hello']) - self.assertEqual('complex', self.calls[0].data['data']['value']) - self.assertEqual('simple', self.calls[0].data['data']['simple']) - self.assertEqual('list', self.calls[0].data['list'][0]) + assert 'goodbye' == self.calls[0].data['hello'] + assert 'complex' == self.calls[0].data['data']['value'] + assert 'simple' == self.calls[0].data['data']['simple'] + assert 'list' == self.calls[0].data['list'][0] def test_passing_variables_to_templates(self): """Test passing variables to templates.""" @@ -66,7 +66,7 @@ class TestServiceHelpers(unittest.TestCase): }) self.hass.block_till_done() - self.assertEqual('goodbye', self.calls[0].data['hello']) + assert 'goodbye' == self.calls[0].data['hello'] def test_bad_template(self): """Test passing bad template.""" @@ -84,7 +84,7 @@ class TestServiceHelpers(unittest.TestCase): }) self.hass.block_till_done() - self.assertEqual(len(self.calls), 0) + assert len(self.calls) == 0 def test_split_entity_string(self): """Test splitting of entity string.""" @@ -93,8 +93,8 @@ class TestServiceHelpers(unittest.TestCase): 'entity_id': 'hello.world, sensor.beer' }) self.hass.block_till_done() - self.assertEqual(['hello.world', 'sensor.beer'], - self.calls[-1].data.get('entity_id')) + assert ['hello.world', 'sensor.beer'] == \ + self.calls[-1].data.get('entity_id') def test_not_mutate_input(self): """Test for immutable input.""" @@ -122,15 +122,15 @@ class TestServiceHelpers(unittest.TestCase): def test_fail_silently_if_no_service(self, mock_log): """Test failing if service is missing.""" service.call_from_config(self.hass, None) - self.assertEqual(1, mock_log.call_count) + assert 1 == mock_log.call_count service.call_from_config(self.hass, {}) - self.assertEqual(2, mock_log.call_count) + assert 2 == mock_log.call_count service.call_from_config(self.hass, { 'service': 'invalid' }) - self.assertEqual(3, mock_log.call_count) + assert 3 == mock_log.call_count def test_extract_entity_ids(self): """Test extract_entity_ids method.""" @@ -144,17 +144,17 @@ class TestServiceHelpers(unittest.TestCase): call = ha.ServiceCall('light', 'turn_on', {ATTR_ENTITY_ID: 'light.Bowl'}) - self.assertEqual(['light.bowl'], - service.extract_entity_ids(self.hass, call)) + assert ['light.bowl'] == \ + service.extract_entity_ids(self.hass, call) call = ha.ServiceCall('light', 'turn_on', {ATTR_ENTITY_ID: 'group.test'}) - self.assertEqual(['light.ceiling', 'light.kitchen'], - service.extract_entity_ids(self.hass, call)) + assert ['light.ceiling', 'light.kitchen'] == \ + service.extract_entity_ids(self.hass, call) - self.assertEqual(['group.test'], service.extract_entity_ids( - self.hass, call, expand_group=False)) + assert ['group.test'] == service.extract_entity_ids( + self.hass, call, expand_group=False) @asyncio.coroutine diff --git a/tests/helpers/test_state.py b/tests/helpers/test_state.py index f230d03e5..076547444 100644 --- a/tests/helpers/test_state.py +++ b/tests/helpers/test_state.py @@ -21,6 +21,7 @@ from homeassistant.components.sun import (STATE_ABOVE_HORIZON, STATE_BELOW_HORIZON) from tests.common import get_test_home_assistant, mock_service +import pytest @asyncio.coroutine @@ -80,9 +81,8 @@ class TestStateHelpers(unittest.TestCase): self.hass.states.set('light.test3', 'on') state3 = self.hass.states.get('light.test3') - self.assertEqual( - [state2, state3], - state.get_changed_since([state1, state2, state3], point2)) + assert [state2, state3] == \ + state.get_changed_since([state1, state2, state3], point2) def test_reproduce_with_no_entity(self): """Test reproduce_state with no entity.""" @@ -92,8 +92,8 @@ class TestStateHelpers(unittest.TestCase): self.hass.block_till_done() - self.assertTrue(len(calls) == 0) - self.assertEqual(None, self.hass.states.get('light.test')) + assert len(calls) == 0 + assert self.hass.states.get('light.test') is None def test_reproduce_turn_on(self): """Test reproduce_state with SERVICE_TURN_ON.""" @@ -105,11 +105,11 @@ class TestStateHelpers(unittest.TestCase): self.hass.block_till_done() - self.assertTrue(len(calls) > 0) + assert len(calls) > 0 last_call = calls[-1] - self.assertEqual('light', last_call.domain) - self.assertEqual(SERVICE_TURN_ON, last_call.service) - self.assertEqual(['light.test'], last_call.data.get('entity_id')) + assert 'light' == last_call.domain + assert SERVICE_TURN_ON == last_call.service + assert ['light.test'] == last_call.data.get('entity_id') def test_reproduce_turn_off(self): """Test reproduce_state with SERVICE_TURN_OFF.""" @@ -121,11 +121,11 @@ class TestStateHelpers(unittest.TestCase): self.hass.block_till_done() - self.assertTrue(len(calls) > 0) + assert len(calls) > 0 last_call = calls[-1] - self.assertEqual('light', last_call.domain) - self.assertEqual(SERVICE_TURN_OFF, last_call.service) - self.assertEqual(['light.test'], last_call.data.get('entity_id')) + assert 'light' == last_call.domain + assert SERVICE_TURN_OFF == last_call.service + assert ['light.test'] == last_call.data.get('entity_id') def test_reproduce_complex_data(self): """Test reproduce_state with complex service data.""" @@ -141,11 +141,11 @@ class TestStateHelpers(unittest.TestCase): self.hass.block_till_done() - self.assertTrue(len(calls) > 0) + assert len(calls) > 0 last_call = calls[-1] - self.assertEqual('light', last_call.domain) - self.assertEqual(SERVICE_TURN_ON, last_call.service) - self.assertEqual(complex_data, last_call.data.get('complex')) + assert 'light' == last_call.domain + assert SERVICE_TURN_ON == last_call.service + assert complex_data == last_call.data.get('complex') def test_reproduce_media_data(self): """Test reproduce_state with SERVICE_PLAY_MEDIA.""" @@ -161,12 +161,12 @@ class TestStateHelpers(unittest.TestCase): self.hass.block_till_done() - self.assertTrue(len(calls) > 0) + assert len(calls) > 0 last_call = calls[-1] - self.assertEqual('media_player', last_call.domain) - self.assertEqual(SERVICE_PLAY_MEDIA, last_call.service) - self.assertEqual('movie', last_call.data.get('media_content_type')) - self.assertEqual('batman', last_call.data.get('media_content_id')) + assert 'media_player' == last_call.domain + assert SERVICE_PLAY_MEDIA == last_call.service + assert 'movie' == last_call.data.get('media_content_type') + assert 'batman' == last_call.data.get('media_content_id') def test_reproduce_media_play(self): """Test reproduce_state with SERVICE_MEDIA_PLAY.""" @@ -179,12 +179,12 @@ class TestStateHelpers(unittest.TestCase): self.hass.block_till_done() - self.assertTrue(len(calls) > 0) + assert len(calls) > 0 last_call = calls[-1] - self.assertEqual('media_player', last_call.domain) - self.assertEqual(SERVICE_MEDIA_PLAY, last_call.service) - self.assertEqual(['media_player.test'], - last_call.data.get('entity_id')) + assert 'media_player' == last_call.domain + assert SERVICE_MEDIA_PLAY == last_call.service + assert ['media_player.test'] == \ + last_call.data.get('entity_id') def test_reproduce_media_pause(self): """Test reproduce_state with SERVICE_MEDIA_PAUSE.""" @@ -197,12 +197,12 @@ class TestStateHelpers(unittest.TestCase): self.hass.block_till_done() - self.assertTrue(len(calls) > 0) + assert len(calls) > 0 last_call = calls[-1] - self.assertEqual('media_player', last_call.domain) - self.assertEqual(SERVICE_MEDIA_PAUSE, last_call.service) - self.assertEqual(['media_player.test'], - last_call.data.get('entity_id')) + assert 'media_player' == last_call.domain + assert SERVICE_MEDIA_PAUSE == last_call.service + assert ['media_player.test'] == \ + last_call.data.get('entity_id') def test_reproduce_bad_state(self): """Test reproduce_state with bad state.""" @@ -214,8 +214,8 @@ class TestStateHelpers(unittest.TestCase): self.hass.block_till_done() - self.assertTrue(len(calls) == 0) - self.assertEqual('off', self.hass.states.get('light.test').state) + assert len(calls) == 0 + assert 'off' == self.hass.states.get('light.test').state def test_reproduce_group(self): """Test reproduce_state with group.""" @@ -228,12 +228,12 @@ class TestStateHelpers(unittest.TestCase): self.hass.block_till_done() - self.assertEqual(1, len(light_calls)) + assert 1 == len(light_calls) last_call = light_calls[-1] - self.assertEqual('light', last_call.domain) - self.assertEqual(SERVICE_TURN_ON, last_call.service) - self.assertEqual(['light.test1', 'light.test2'], - last_call.data.get('entity_id')) + assert 'light' == last_call.domain + assert SERVICE_TURN_ON == last_call.service + assert ['light.test1', 'light.test2'] == \ + last_call.data.get('entity_id') def test_reproduce_group_same_data(self): """Test reproduce_state with group with same domain and data.""" @@ -248,13 +248,13 @@ class TestStateHelpers(unittest.TestCase): self.hass.block_till_done() - self.assertEqual(1, len(light_calls)) + assert 1 == len(light_calls) last_call = light_calls[-1] - self.assertEqual('light', last_call.domain) - self.assertEqual(SERVICE_TURN_ON, last_call.service) - self.assertEqual(['light.test1', 'light.test2'], - last_call.data.get('entity_id')) - self.assertEqual(95, last_call.data.get('brightness')) + assert 'light' == last_call.domain + assert SERVICE_TURN_ON == last_call.service + assert ['light.test1', 'light.test2'] == \ + last_call.data.get('entity_id') + assert 95 == last_call.data.get('brightness') def test_as_number_states(self): """Test state_as_number with states.""" @@ -263,27 +263,24 @@ class TestStateHelpers(unittest.TestCase): one_states = (STATE_ON, STATE_OPEN, STATE_LOCKED, STATE_ABOVE_HORIZON, STATE_HOME) for _state in zero_states: - self.assertEqual(0, state.state_as_number( - ha.State('domain.test', _state, {}))) + assert 0 == state.state_as_number( + ha.State('domain.test', _state, {})) for _state in one_states: - self.assertEqual(1, state.state_as_number( - ha.State('domain.test', _state, {}))) + assert 1 == state.state_as_number( + ha.State('domain.test', _state, {})) def test_as_number_coercion(self): """Test state_as_number with number.""" for _state in ('0', '0.0', 0, 0.0): - self.assertEqual( - 0.0, state.state_as_number( - ha.State('domain.test', _state, {}))) + assert 0.0 == state.state_as_number( + ha.State('domain.test', _state, {})) for _state in ('1', '1.0', 1, 1.0): - self.assertEqual( - 1.0, state.state_as_number( - ha.State('domain.test', _state, {}))) + assert 1.0 == state.state_as_number( + ha.State('domain.test', _state, {})) def test_as_number_invalid_cases(self): """Test state_as_number with invalid cases.""" for _state in ('', 'foo', 'foo.bar', None, False, True, object, object()): - self.assertRaises(ValueError, - state.state_as_number, - ha.State('domain.test', _state, {})) + with pytest.raises(ValueError): + state.state_as_number(ha.State('domain.test', _state, {})) diff --git a/tests/helpers/test_sun.py b/tests/helpers/test_sun.py index b1c7f62e7..8fb4e44b0 100644 --- a/tests/helpers/test_sun.py +++ b/tests/helpers/test_sun.py @@ -83,18 +83,18 @@ class TestSun(unittest.TestCase): with patch('homeassistant.helpers.condition.dt_util.utcnow', return_value=utc_now): - self.assertEqual(next_dawn, sun.get_astral_event_next( - self.hass, 'dawn')) - self.assertEqual(next_dusk, sun.get_astral_event_next( - self.hass, 'dusk')) - self.assertEqual(next_midnight, sun.get_astral_event_next( - self.hass, 'solar_midnight')) - self.assertEqual(next_noon, sun.get_astral_event_next( - self.hass, 'solar_noon')) - self.assertEqual(next_rising, sun.get_astral_event_next( - self.hass, 'sunrise')) - self.assertEqual(next_setting, sun.get_astral_event_next( - self.hass, 'sunset')) + assert next_dawn == sun.get_astral_event_next( + self.hass, 'dawn') + assert next_dusk == sun.get_astral_event_next( + self.hass, 'dusk') + assert next_midnight == sun.get_astral_event_next( + self.hass, 'solar_midnight') + assert next_noon == sun.get_astral_event_next( + self.hass, 'solar_noon') + assert next_rising == sun.get_astral_event_next( + self.hass, 'sunrise') + assert next_setting == sun.get_astral_event_next( + self.hass, 'sunset') def test_date_events(self): """Test retrieving next sun events.""" @@ -114,18 +114,18 @@ class TestSun(unittest.TestCase): sunrise = astral.sunrise_utc(utc_today, latitude, longitude) sunset = astral.sunset_utc(utc_today, latitude, longitude) - self.assertEqual(dawn, sun.get_astral_event_date( - self.hass, 'dawn', utc_today)) - self.assertEqual(dusk, sun.get_astral_event_date( - self.hass, 'dusk', utc_today)) - self.assertEqual(midnight, sun.get_astral_event_date( - self.hass, 'solar_midnight', utc_today)) - self.assertEqual(noon, sun.get_astral_event_date( - self.hass, 'solar_noon', utc_today)) - self.assertEqual(sunrise, sun.get_astral_event_date( - self.hass, 'sunrise', utc_today)) - self.assertEqual(sunset, sun.get_astral_event_date( - self.hass, 'sunset', utc_today)) + assert dawn == sun.get_astral_event_date( + self.hass, 'dawn', utc_today) + assert dusk == sun.get_astral_event_date( + self.hass, 'dusk', utc_today) + assert midnight == sun.get_astral_event_date( + self.hass, 'solar_midnight', utc_today) + assert noon == sun.get_astral_event_date( + self.hass, 'solar_noon', utc_today) + assert sunrise == sun.get_astral_event_date( + self.hass, 'sunrise', utc_today) + assert sunset == sun.get_astral_event_date( + self.hass, 'sunset', utc_today) def test_date_events_default_date(self): """Test retrieving next sun events.""" @@ -146,18 +146,18 @@ class TestSun(unittest.TestCase): sunset = astral.sunset_utc(utc_today, latitude, longitude) with patch('homeassistant.util.dt.now', return_value=utc_now): - self.assertEqual(dawn, sun.get_astral_event_date( - self.hass, 'dawn', utc_today)) - self.assertEqual(dusk, sun.get_astral_event_date( - self.hass, 'dusk', utc_today)) - self.assertEqual(midnight, sun.get_astral_event_date( - self.hass, 'solar_midnight', utc_today)) - self.assertEqual(noon, sun.get_astral_event_date( - self.hass, 'solar_noon', utc_today)) - self.assertEqual(sunrise, sun.get_astral_event_date( - self.hass, 'sunrise', utc_today)) - self.assertEqual(sunset, sun.get_astral_event_date( - self.hass, 'sunset', utc_today)) + assert dawn == sun.get_astral_event_date( + self.hass, 'dawn', utc_today) + assert dusk == sun.get_astral_event_date( + self.hass, 'dusk', utc_today) + assert midnight == sun.get_astral_event_date( + self.hass, 'solar_midnight', utc_today) + assert noon == sun.get_astral_event_date( + self.hass, 'solar_noon', utc_today) + assert sunrise == sun.get_astral_event_date( + self.hass, 'sunrise', utc_today) + assert sunset == sun.get_astral_event_date( + self.hass, 'sunset', utc_today) def test_date_events_accepts_datetime(self): """Test retrieving next sun events.""" @@ -177,30 +177,30 @@ class TestSun(unittest.TestCase): sunrise = astral.sunrise_utc(utc_today, latitude, longitude) sunset = astral.sunset_utc(utc_today, latitude, longitude) - self.assertEqual(dawn, sun.get_astral_event_date( - self.hass, 'dawn', utc_now)) - self.assertEqual(dusk, sun.get_astral_event_date( - self.hass, 'dusk', utc_now)) - self.assertEqual(midnight, sun.get_astral_event_date( - self.hass, 'solar_midnight', utc_now)) - self.assertEqual(noon, sun.get_astral_event_date( - self.hass, 'solar_noon', utc_now)) - self.assertEqual(sunrise, sun.get_astral_event_date( - self.hass, 'sunrise', utc_now)) - self.assertEqual(sunset, sun.get_astral_event_date( - self.hass, 'sunset', utc_now)) + assert dawn == sun.get_astral_event_date( + self.hass, 'dawn', utc_now) + assert dusk == sun.get_astral_event_date( + self.hass, 'dusk', utc_now) + assert midnight == sun.get_astral_event_date( + self.hass, 'solar_midnight', utc_now) + assert noon == sun.get_astral_event_date( + self.hass, 'solar_noon', utc_now) + assert sunrise == sun.get_astral_event_date( + self.hass, 'sunrise', utc_now) + assert sunset == sun.get_astral_event_date( + self.hass, 'sunset', utc_now) def test_is_up(self): """Test retrieving next sun events.""" utc_now = datetime(2016, 11, 1, 12, 0, 0, tzinfo=dt_util.UTC) with patch('homeassistant.helpers.condition.dt_util.utcnow', return_value=utc_now): - self.assertFalse(sun.is_up(self.hass)) + assert not sun.is_up(self.hass) utc_now = datetime(2016, 11, 1, 18, 0, 0, tzinfo=dt_util.UTC) with patch('homeassistant.helpers.condition.dt_util.utcnow', return_value=utc_now): - self.assertTrue(sun.is_up(self.hass)) + assert sun.is_up(self.hass) def test_norway_in_june(self): """Test location in Norway where the sun doesn't set in summer.""" diff --git a/tests/helpers/test_temperature.py b/tests/helpers/test_temperature.py index e2366d886..f6bee7b12 100644 --- a/tests/helpers/test_temperature.py +++ b/tests/helpers/test_temperature.py @@ -8,6 +8,7 @@ from homeassistant.const import ( PRECISION_TENTHS) from homeassistant.helpers.temperature import display_temp from homeassistant.util.unit_system import METRIC_SYSTEM +import pytest TEMP = 24.636626 @@ -27,23 +28,23 @@ class TestHelpersTemperature(unittest.TestCase): def test_temperature_not_a_number(self): """Test that temperature is a number.""" temp = "Temperature" - with self.assertRaises(Exception) as context: + with pytest.raises(Exception) as exception: display_temp(self.hass, temp, TEMP_CELSIUS, PRECISION_HALVES) - self.assertTrue("Temperature is not a number: {}".format(temp) - in str(context.exception)) + assert "Temperature is not a number: {}".format(temp) \ + in str(exception) def test_celsius_halves(self): """Test temperature to celsius rounding to halves.""" - self.assertEqual(24.5, display_temp( - self.hass, TEMP, TEMP_CELSIUS, PRECISION_HALVES)) + assert 24.5 == display_temp( + self.hass, TEMP, TEMP_CELSIUS, PRECISION_HALVES) def test_celsius_tenths(self): """Test temperature to celsius rounding to tenths.""" - self.assertEqual(24.6, display_temp( - self.hass, TEMP, TEMP_CELSIUS, PRECISION_TENTHS)) + assert 24.6 == display_temp( + self.hass, TEMP, TEMP_CELSIUS, PRECISION_TENTHS) def test_fahrenheit_wholes(self): """Test temperature to fahrenheit rounding to wholes.""" - self.assertEqual(-4, display_temp( - self.hass, TEMP, TEMP_FAHRENHEIT, PRECISION_WHOLE)) + assert -4 == display_temp( + self.hass, TEMP, TEMP_FAHRENHEIT, PRECISION_WHOLE) diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 2ead38ba3..802138898 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -20,6 +20,7 @@ from homeassistant.const import ( import homeassistant.util.dt as dt_util from tests.common import get_test_home_assistant +import pytest class TestHelpersTemplate(unittest.TestCase): @@ -41,21 +42,19 @@ class TestHelpersTemplate(unittest.TestCase): def test_referring_states_by_entity_id(self): """Test referring states by entity id.""" self.hass.states.set('test.object', 'happy') - self.assertEqual( - 'happy', + assert 'happy' == \ template.Template( - '{{ states.test.object.state }}', self.hass).render()) + '{{ states.test.object.state }}', self.hass).render() def test_iterating_all_states(self): """Test iterating all states.""" self.hass.states.set('test.object', 'happy') self.hass.states.set('sensor.temperature', 10) - self.assertEqual( - '10happy', + assert '10happy' == \ template.Template( '{% for state in states %}{{ state.state }}{% endfor %}', - self.hass).render()) + self.hass).render() def test_iterating_domain_states(self): """Test iterating domain states.""" @@ -63,54 +62,47 @@ class TestHelpersTemplate(unittest.TestCase): self.hass.states.set('sensor.back_door', 'open') self.hass.states.set('sensor.temperature', 10) - self.assertEqual( - 'open10', + assert 'open10' == \ template.Template(""" {% for state in states.sensor %}{{ state.state }}{% endfor %} - """, self.hass).render()) + """, self.hass).render() def test_float(self): """Test float.""" self.hass.states.set('sensor.temperature', '12') - self.assertEqual( - '12.0', + assert '12.0' == \ template.Template( '{{ float(states.sensor.temperature.state) }}', - self.hass).render()) + self.hass).render() - self.assertEqual( - 'True', + assert 'True' == \ template.Template( '{{ float(states.sensor.temperature.state) > 11 }}', - self.hass).render()) + self.hass).render() def test_rounding_value(self): """Test rounding value.""" self.hass.states.set('sensor.temperature', 12.78) - self.assertEqual( - '12.8', + assert '12.8' == \ template.Template( '{{ states.sensor.temperature.state | round(1) }}', - self.hass).render()) + self.hass).render() - self.assertEqual( - '128', + assert '128' == \ template.Template( '{{ states.sensor.temperature.state | multiply(10) | round }}', - self.hass).render()) + self.hass).render() def test_rounding_value_get_original_value_on_error(self): """Test rounding value get original value on error.""" - self.assertEqual( - 'None', - template.Template('{{ None | round }}', self.hass).render()) + assert 'None' == \ + template.Template('{{ None | round }}', self.hass).render() - self.assertEqual( - 'no_number', + assert 'no_number' == \ template.Template( - '{{ "no_number" | round }}', self.hass).render()) + '{{ "no_number" | round }}', self.hass).render() def test_multiply(self): """Test multiply.""" @@ -121,10 +113,9 @@ class TestHelpersTemplate(unittest.TestCase): } for inp, out in tests.items(): - self.assertEqual( - out, + assert out == \ template.Template('{{ %s | multiply(10) | round }}' % inp, - self.hass).render()) + self.hass).render() def test_logarithm(self): """Test logarithm.""" @@ -137,17 +128,15 @@ class TestHelpersTemplate(unittest.TestCase): ] for value, base, expected in tests: - self.assertEqual( - expected, + assert expected == \ template.Template( '{{ %s | log(%s) | round(1) }}' % (value, base), - self.hass).render()) + self.hass).render() - self.assertEqual( - expected, + assert expected == \ template.Template( '{{ log(%s, %s) | round(1) }}' % (value, base), - self.hass).render()) + self.hass).render() def test_sine(self): """Test sine.""" @@ -160,11 +149,10 @@ class TestHelpersTemplate(unittest.TestCase): ] for value, expected in tests: - self.assertEqual( - expected, + assert expected == \ template.Template( '{{ %s | sin | round(3) }}' % value, - self.hass).render()) + self.hass).render() def test_cos(self): """Test cosine.""" @@ -177,11 +165,10 @@ class TestHelpersTemplate(unittest.TestCase): ] for value, expected in tests: - self.assertEqual( - expected, + assert expected == \ template.Template( '{{ %s | cos | round(3) }}' % value, - self.hass).render()) + self.hass).render() def test_tan(self): """Test tangent.""" @@ -194,11 +181,10 @@ class TestHelpersTemplate(unittest.TestCase): ] for value, expected in tests: - self.assertEqual( - expected, + assert expected == \ template.Template( '{{ %s | tan | round(3) }}' % value, - self.hass).render()) + self.hass).render() def test_sqrt(self): """Test square root.""" @@ -211,11 +197,10 @@ class TestHelpersTemplate(unittest.TestCase): ] for value, expected in tests: - self.assertEqual( - expected, + assert expected == \ template.Template( '{{ %s | sqrt | round(3) }}' % value, - self.hass).render()) + self.hass).render() def test_strptime(self): """Test the parse timestamp method.""" @@ -239,9 +224,8 @@ class TestHelpersTemplate(unittest.TestCase): temp = '{{ strptime(\'%s\', \'%s\') }}' % (inp, fmt) - self.assertEqual( - str(expected), - template.Template(temp, self.hass).render()) + assert str(expected) == \ + template.Template(temp, self.hass).render() def test_timestamp_custom(self): """Test the timestamps to custom filter.""" @@ -263,10 +247,8 @@ class TestHelpersTemplate(unittest.TestCase): else: fil = 'timestamp_custom' - self.assertEqual( - out, - template.Template('{{ %s | %s }}' % (inp, fil), - self.hass).render()) + assert out == template.Template( + '{{ %s | %s }}' % (inp, fil), self.hass).render() def test_timestamp_local(self): """Test the timestamps to local filter.""" @@ -276,24 +258,21 @@ class TestHelpersTemplate(unittest.TestCase): } for inp, out in tests.items(): - self.assertEqual( - out, + assert out == \ template.Template('{{ %s | timestamp_local }}' % inp, - self.hass).render()) + self.hass).render() def test_min(self): """Test the min filter.""" - self.assertEqual( - '1', + assert '1' == \ template.Template('{{ [1, 2, 3] | min }}', - self.hass).render()) + self.hass).render() def test_max(self): """Test the max filter.""" - self.assertEqual( - '3', + assert '3' == \ template.Template('{{ [1, 2, 3] | max }}', - self.hass).render()) + self.hass).render() def test_timestamp_utc(self): """Test the timestamps to local filter.""" @@ -306,129 +285,115 @@ class TestHelpersTemplate(unittest.TestCase): } for inp, out in tests.items(): - self.assertEqual( - out, + assert out == \ template.Template('{{ %s | timestamp_utc }}' % inp, - self.hass).render()) + self.hass).render() def test_as_timestamp(self): """Test the as_timestamp function.""" - self.assertEqual("None", - template.Template('{{ as_timestamp("invalid") }}', - self.hass).render()) + assert "None" == \ + template.Template( + '{{ as_timestamp("invalid") }}', self.hass).render() self.hass.mock = None - self.assertEqual("None", - template.Template('{{ as_timestamp(states.mock) }}', - self.hass).render()) + assert "None" == \ + template.Template('{{ as_timestamp(states.mock) }}', + self.hass).render() tpl = '{{ as_timestamp(strptime("2024-02-03T09:10:24+0000", ' \ '"%Y-%m-%dT%H:%M:%S%z")) }}' - self.assertEqual("1706951424.0", - template.Template(tpl, self.hass).render()) + assert "1706951424.0" == \ + template.Template(tpl, self.hass).render() @patch.object(random, 'choice') def test_random_every_time(self, test_choice): """Ensure the random filter runs every time, not just once.""" tpl = template.Template('{{ [1,2] | random }}', self.hass) test_choice.return_value = 'foo' - self.assertEqual('foo', tpl.render()) + assert 'foo' == tpl.render() test_choice.return_value = 'bar' - self.assertEqual('bar', tpl.render()) + assert 'bar' == tpl.render() def test_passing_vars_as_keywords(self): """Test passing variables as keywords.""" - self.assertEqual( - '127', - template.Template('{{ hello }}', self.hass).render(hello=127)) + assert '127' == \ + template.Template('{{ hello }}', self.hass).render(hello=127) def test_passing_vars_as_vars(self): """Test passing variables as variables.""" - self.assertEqual( - '127', - template.Template('{{ hello }}', self.hass).render({'hello': 127})) + assert '127' == \ + template.Template('{{ hello }}', self.hass).render({'hello': 127}) def test_passing_vars_as_list(self): """Test passing variables as list.""" - self.assertEqual( - "['foo', 'bar']", + assert "['foo', 'bar']" == \ template.render_complex(template.Template('{{ hello }}', - self.hass), {'hello': ['foo', 'bar']})) + self.hass), {'hello': ['foo', 'bar']}) def test_passing_vars_as_list_element(self): """Test passing variables as list.""" - self.assertEqual( - 'bar', + assert 'bar' == \ template.render_complex(template.Template('{{ hello[1] }}', self.hass), - {'hello': ['foo', 'bar']})) + {'hello': ['foo', 'bar']}) def test_passing_vars_as_dict_element(self): """Test passing variables as list.""" - self.assertEqual( - 'bar', + assert 'bar' == \ template.render_complex(template.Template('{{ hello.foo }}', self.hass), - {'hello': {'foo': 'bar'}})) + {'hello': {'foo': 'bar'}}) def test_passing_vars_as_dict(self): """Test passing variables as list.""" - self.assertEqual( - "{'foo': 'bar'}", + assert "{'foo': 'bar'}" == \ template.render_complex(template.Template('{{ hello }}', - self.hass), {'hello': {'foo': 'bar'}})) + self.hass), {'hello': {'foo': 'bar'}}) def test_render_with_possible_json_value_with_valid_json(self): """Render with possible JSON value with valid JSON.""" tpl = template.Template('{{ value_json.hello }}', self.hass) - self.assertEqual( - 'world', - tpl.render_with_possible_json_value('{"hello": "world"}')) + assert 'world' == \ + tpl.render_with_possible_json_value('{"hello": "world"}') def test_render_with_possible_json_value_with_invalid_json(self): """Render with possible JSON value with invalid JSON.""" tpl = template.Template('{{ value_json }}', self.hass) - self.assertEqual( - '', - tpl.render_with_possible_json_value('{ I AM NOT JSON }')) + assert '' == \ + tpl.render_with_possible_json_value('{ I AM NOT JSON }') def test_render_with_possible_json_value_with_template_error_value(self): """Render with possible JSON value with template error value.""" tpl = template.Template('{{ non_existing.variable }}', self.hass) - self.assertEqual( - '-', - tpl.render_with_possible_json_value('hello', '-')) + assert '-' == \ + tpl.render_with_possible_json_value('hello', '-') def test_render_with_possible_json_value_with_missing_json_value(self): """Render with possible JSON value with unknown JSON object.""" tpl = template.Template('{{ value_json.goodbye }}', self.hass) - self.assertEqual( - '', - tpl.render_with_possible_json_value('{"hello": "world"}')) + assert '' == \ + tpl.render_with_possible_json_value('{"hello": "world"}') def test_render_with_possible_json_value_valid_with_is_defined(self): """Render with possible JSON value with known JSON object.""" tpl = template.Template('{{ value_json.hello|is_defined }}', self.hass) - self.assertEqual( - 'world', - tpl.render_with_possible_json_value('{"hello": "world"}')) + assert 'world' == \ + tpl.render_with_possible_json_value('{"hello": "world"}') def test_render_with_possible_json_value_undefined_json(self): """Render with possible JSON value with unknown JSON object.""" tpl = template.Template('{{ value_json.bye|is_defined }}', self.hass) - self.assertEqual( - '{"hello": "world"}', - tpl.render_with_possible_json_value('{"hello": "world"}')) + assert '{"hello": "world"}' == \ + tpl.render_with_possible_json_value('{"hello": "world"}') def test_render_with_possible_json_value_undefined_json_error_value(self): """Render with possible JSON value with unknown JSON object.""" tpl = template.Template('{{ value_json.bye|is_defined }}', self.hass) - self.assertEqual( - '', - tpl.render_with_possible_json_value('{"hello": "world"}', '')) + assert '' == \ + tpl.render_with_possible_json_value('{"hello": "world"}', '') def test_raise_exception_on_error(self): """Test raising an exception on error.""" - with self.assertRaises(TemplateError): + with pytest.raises(TemplateError): template.Template('{{ invalid_syntax').ensure_valid() def test_if_state_exists(self): @@ -437,7 +402,7 @@ class TestHelpersTemplate(unittest.TestCase): tpl = template.Template( '{% if states.test.object %}exists{% else %}not exists{% endif %}', self.hass) - self.assertEqual('exists', tpl.render()) + assert 'exists' == tpl.render() def test_is_state(self): """Test is_state method.""" @@ -445,12 +410,12 @@ class TestHelpersTemplate(unittest.TestCase): tpl = template.Template(""" {% if is_state("test.object", "available") %}yes{% else %}no{% endif %} """, self.hass) - self.assertEqual('yes', tpl.render()) + assert 'yes' == tpl.render() tpl = template.Template(""" {{ is_state("test.noobject", "available") }} """, self.hass) - self.assertEqual('False', tpl.render()) + assert 'False' == tpl.render() def test_is_state_attr(self): """Test is_state_attr method.""" @@ -458,12 +423,12 @@ class TestHelpersTemplate(unittest.TestCase): tpl = template.Template(""" {% if is_state_attr("test.object", "mode", "on") %}yes{% else %}no{% endif %} """, self.hass) - self.assertEqual('yes', tpl.render()) + assert 'yes' == tpl.render() tpl = template.Template(""" {{ is_state_attr("test.noobject", "mode", "on") }} """, self.hass) - self.assertEqual('False', tpl.render()) + assert 'False' == tpl.render() def test_state_attr(self): """Test state_attr method.""" @@ -471,21 +436,21 @@ class TestHelpersTemplate(unittest.TestCase): tpl = template.Template(""" {% if state_attr("test.object", "mode") == "on" %}yes{% else %}no{% endif %} """, self.hass) - self.assertEqual('yes', tpl.render()) + assert 'yes' == tpl.render() tpl = template.Template(""" {{ state_attr("test.noobject", "mode") == None }} """, self.hass) - self.assertEqual('True', tpl.render()) + assert 'True' == tpl.render() def test_states_function(self): """Test using states as a function.""" self.hass.states.set('test.object', 'available') tpl = template.Template('{{ states("test.object") }}', self.hass) - self.assertEqual('available', tpl.render()) + assert 'available' == tpl.render() tpl2 = template.Template('{{ states("test.object2") }}', self.hass) - self.assertEqual('unknown', tpl2.render()) + assert 'unknown' == tpl2.render() @patch('homeassistant.helpers.template.TemplateEnvironment.' 'is_safe_callable', return_value=True) @@ -493,10 +458,9 @@ class TestHelpersTemplate(unittest.TestCase): """Test now method.""" now = dt_util.now() with patch.dict(template.ENV.globals, {'now': lambda: now}): - self.assertEqual( - now.isoformat(), + assert now.isoformat() == \ template.Template('{{ now().isoformat() }}', - self.hass).render()) + self.hass).render() @patch('homeassistant.helpers.template.TemplateEnvironment.' 'is_safe_callable', return_value=True) @@ -504,93 +468,92 @@ class TestHelpersTemplate(unittest.TestCase): """Test utcnow method.""" now = dt_util.utcnow() with patch.dict(template.ENV.globals, {'utcnow': lambda: now}): - self.assertEqual( - now.isoformat(), + assert now.isoformat() == \ template.Template('{{ utcnow().isoformat() }}', - self.hass).render()) + self.hass).render() def test_regex_match(self): """Test regex_match method.""" tpl = template.Template(r""" {{ '123-456-7890' | regex_match('(\\d{3})-(\\d{3})-(\\d{4})') }} """, self.hass) - self.assertEqual('True', tpl.render()) + assert 'True' == tpl.render() tpl = template.Template(""" {{ 'home assistant test' | regex_match('Home', True) }} """, self.hass) - self.assertEqual('True', tpl.render()) + assert 'True' == tpl.render() tpl = template.Template(""" {{ 'Another home assistant test' | regex_match('home') }} """, self.hass) - self.assertEqual('False', tpl.render()) + assert 'False' == tpl.render() def test_regex_search(self): """Test regex_search method.""" tpl = template.Template(r""" {{ '123-456-7890' | regex_search('(\\d{3})-(\\d{3})-(\\d{4})') }} """, self.hass) - self.assertEqual('True', tpl.render()) + assert 'True' == tpl.render() tpl = template.Template(""" {{ 'home assistant test' | regex_search('Home', True) }} """, self.hass) - self.assertEqual('True', tpl.render()) + assert 'True' == tpl.render() tpl = template.Template(""" {{ 'Another home assistant test' | regex_search('home') }} """, self.hass) - self.assertEqual('True', tpl.render()) + assert 'True' == tpl.render() def test_regex_replace(self): """Test regex_replace method.""" tpl = template.Template(r""" {{ 'Hello World' | regex_replace('(Hello\\s)',) }} """, self.hass) - self.assertEqual('World', tpl.render()) + assert 'World' == tpl.render() def test_regex_findall_index(self): """Test regex_findall_index method.""" tpl = template.Template(""" {{ 'Flight from JFK to LHR' | regex_findall_index('([A-Z]{3})', 0) }} """, self.hass) - self.assertEqual('JFK', tpl.render()) + assert 'JFK' == tpl.render() tpl = template.Template(""" {{ 'Flight from JFK to LHR' | regex_findall_index('([A-Z]{3})', 1) }} """, self.hass) - self.assertEqual('LHR', tpl.render()) + assert 'LHR' == tpl.render() def test_bitwise_and(self): """Test bitwise_and method.""" tpl = template.Template(""" {{ 8 | bitwise_and(8) }} """, self.hass) - self.assertEqual(str(8 & 8), tpl.render()) + assert str(8 & 8) == tpl.render() tpl = template.Template(""" {{ 10 | bitwise_and(2) }} """, self.hass) - self.assertEqual(str(10 & 2), tpl.render()) + assert str(10 & 2) == tpl.render() tpl = template.Template(""" {{ 8 | bitwise_and(2) }} """, self.hass) - self.assertEqual(str(8 & 2), tpl.render()) + assert str(8 & 2) == tpl.render() def test_bitwise_or(self): """Test bitwise_or method.""" tpl = template.Template(""" {{ 8 | bitwise_or(8) }} """, self.hass) - self.assertEqual(str(8 | 8), tpl.render()) + assert str(8 | 8) == tpl.render() tpl = template.Template(""" {{ 10 | bitwise_or(2) }} """, self.hass) - self.assertEqual(str(10 | 2), tpl.render()) + assert str(10 | 2) == tpl.render() tpl = template.Template(""" {{ 8 | bitwise_or(2) }} """, self.hass) - self.assertEqual(str(8 | 2), tpl.render()) + assert str(8 | 2) == tpl.render() def test_distance_function_with_1_state(self): """Test distance function with 1 state.""" @@ -600,7 +563,7 @@ class TestHelpersTemplate(unittest.TestCase): }) tpl = template.Template('{{ distance(states.test.object) | round }}', self.hass) - self.assertEqual('187', tpl.render()) + assert '187' == tpl.render() def test_distance_function_with_2_states(self): """Test distance function with 2 states.""" @@ -615,24 +578,22 @@ class TestHelpersTemplate(unittest.TestCase): tpl = template.Template( '{{ distance(states.test.object, states.test.object_2) | round }}', self.hass) - self.assertEqual('187', tpl.render()) + assert '187' == tpl.render() def test_distance_function_with_1_coord(self): """Test distance function with 1 coord.""" tpl = template.Template( '{{ distance("32.87336", "-117.22943") | round }}', self.hass) - self.assertEqual( - '187', - tpl.render()) + assert '187' == \ + tpl.render() def test_distance_function_with_2_coords(self): """Test distance function with 2 coords.""" - self.assertEqual( - '187', + assert '187' == \ template.Template( '{{ distance("32.87336", "-117.22943", %s, %s) | round }}' % (self.hass.config.latitude, self.hass.config.longitude), - self.hass).render()) + self.hass).render() def test_distance_function_with_1_state_1_coord(self): """Test distance function with 1 state 1 coord.""" @@ -643,12 +604,12 @@ class TestHelpersTemplate(unittest.TestCase): tpl = template.Template( '{{ distance("32.87336", "-117.22943", states.test.object_2) ' '| round }}', self.hass) - self.assertEqual('187', tpl.render()) + assert '187' == tpl.render() tpl2 = template.Template( '{{ distance(states.test.object_2, "32.87336", "-117.22943") ' '| round }}', self.hass) - self.assertEqual('187', tpl2.render()) + assert '187' == tpl2.render() def test_distance_function_return_None_if_invalid_state(self): """Test distance function return None if invalid state.""" @@ -657,20 +618,17 @@ class TestHelpersTemplate(unittest.TestCase): }) tpl = template.Template('{{ distance(states.test.object_2) | round }}', self.hass) - self.assertEqual( - 'None', - tpl.render()) + assert 'None' == \ + tpl.render() def test_distance_function_return_None_if_invalid_coord(self): """Test distance function return None if invalid coord.""" - self.assertEqual( - 'None', + assert 'None' == \ template.Template( - '{{ distance("123", "abc") }}', self.hass).render()) + '{{ distance("123", "abc") }}', self.hass).render() - self.assertEqual( - 'None', - template.Template('{{ distance("123") }}', self.hass).render()) + assert 'None' == \ + template.Template('{{ distance("123") }}', self.hass).render() self.hass.states.set('test.object_2', 'happy', { 'latitude': self.hass.config.latitude, @@ -678,9 +636,8 @@ class TestHelpersTemplate(unittest.TestCase): }) tpl = template.Template('{{ distance("123", states.test_object_2) }}', self.hass) - self.assertEqual( - 'None', - tpl.render()) + assert 'None' == \ + tpl.render() def test_distance_function_with_2_entity_ids(self): """Test distance function with 2 entity ids.""" @@ -695,7 +652,7 @@ class TestHelpersTemplate(unittest.TestCase): tpl = template.Template( '{{ distance("test.object", "test.object_2") | round }}', self.hass) - self.assertEqual('187', tpl.render()) + assert '187' == tpl.render() def test_distance_function_with_1_entity_1_coord(self): """Test distance function with 1 entity_id and 1 coord.""" @@ -706,7 +663,7 @@ class TestHelpersTemplate(unittest.TestCase): tpl = template.Template( '{{ distance("test.object", "32.87336", "-117.22943") | round }}', self.hass) - self.assertEqual('187', tpl.render()) + assert '187' == tpl.render() def test_closest_function_home_vs_domain(self): """Test closest function home vs domain.""" @@ -720,10 +677,9 @@ class TestHelpersTemplate(unittest.TestCase): 'longitude': self.hass.config.longitude, }) - self.assertEqual( - 'test_domain.object', + assert 'test_domain.object' == \ template.Template('{{ closest(states.test_domain).entity_id }}', - self.hass).render()) + self.hass).render() def test_closest_function_home_vs_all_states(self): """Test closest function home vs all states.""" @@ -737,10 +693,9 @@ class TestHelpersTemplate(unittest.TestCase): 'longitude': self.hass.config.longitude, }) - self.assertEqual( - 'test_domain_2.and_closer', + assert 'test_domain_2.and_closer' == \ template.Template('{{ closest(states).entity_id }}', - self.hass).render()) + self.hass).render() def test_closest_function_home_vs_group_entity_id(self): """Test closest function home vs group entity id.""" @@ -757,11 +712,10 @@ class TestHelpersTemplate(unittest.TestCase): group.Group.create_group( self.hass, 'location group', ['test_domain.object']) - self.assertEqual( - 'test_domain.object', + assert 'test_domain.object' == \ template.Template( '{{ closest("group.location_group").entity_id }}', - self.hass).render()) + self.hass).render() def test_closest_function_home_vs_group_state(self): """Test closest function home vs group state.""" @@ -778,11 +732,10 @@ class TestHelpersTemplate(unittest.TestCase): group.Group.create_group( self.hass, 'location group', ['test_domain.object']) - self.assertEqual( - 'test_domain.object', + assert 'test_domain.object' == \ template.Template( '{{ closest(states.group.location_group).entity_id }}', - self.hass).render()) + self.hass).render() def test_closest_function_to_coord(self): """Test closest function to coord.""" @@ -806,9 +759,8 @@ class TestHelpersTemplate(unittest.TestCase): % (self.hass.config.latitude + 0.3, self.hass.config.longitude + 0.3), self.hass) - self.assertEqual( - 'test_domain.closest_zone', - tpl.render()) + assert 'test_domain.closest_zone' == \ + tpl.render() def test_closest_function_to_entity_id(self): """Test closest function to entity id.""" @@ -827,11 +779,10 @@ class TestHelpersTemplate(unittest.TestCase): 'longitude': self.hass.config.longitude + 0.3, }) - self.assertEqual( - 'test_domain.closest_zone', + assert 'test_domain.closest_zone' == \ template.Template( '{{ closest("zone.far_away", ' - 'states.test_domain).entity_id }}', self.hass).render()) + 'states.test_domain).entity_id }}', self.hass).render() def test_closest_function_to_state(self): """Test closest function to state.""" @@ -850,11 +801,10 @@ class TestHelpersTemplate(unittest.TestCase): 'longitude': self.hass.config.longitude + 0.3, }) - self.assertEqual( - 'test_domain.closest_zone', + assert 'test_domain.closest_zone' == \ template.Template( '{{ closest(states.zone.far_away, ' - 'states.test_domain).entity_id }}', self.hass).render()) + 'states.test_domain).entity_id }}', self.hass).render() def test_closest_function_invalid_state(self): """Test closest function invalid state.""" @@ -864,10 +814,9 @@ class TestHelpersTemplate(unittest.TestCase): }) for state in ('states.zone.non_existing', '"zone.non_existing"'): - self.assertEqual( - 'None', + assert 'None' == \ template.Template('{{ closest(%s, states) }}' % state, - self.hass).render()) + self.hass).render() def test_closest_function_state_with_invalid_location(self): """Test closest function state with invalid location.""" @@ -876,11 +825,10 @@ class TestHelpersTemplate(unittest.TestCase): 'longitude': self.hass.config.longitude + 0.1, }) - self.assertEqual( - 'None', + assert 'None' == \ template.Template( '{{ closest(states.test_domain.closest_home, ' - 'states) }}', self.hass).render()) + 'states) }}', self.hass).render() def test_closest_function_invalid_coordinates(self): """Test closest function invalid coordinates.""" @@ -889,148 +837,129 @@ class TestHelpersTemplate(unittest.TestCase): 'longitude': self.hass.config.longitude + 0.1, }) - self.assertEqual( - 'None', + assert 'None' == \ template.Template('{{ closest("invalid", "coord", states) }}', - self.hass).render()) + self.hass).render() def test_closest_function_no_location_states(self): """Test closest function without location states.""" - self.assertEqual( - '', + assert '' == \ template.Template('{{ closest(states).entity_id }}', - self.hass).render()) + self.hass).render() def test_extract_entities_none_exclude_stuff(self): """Test extract entities function with none or exclude stuff.""" - self.assertEqual(MATCH_ALL, template.extract_entities(None)) + assert MATCH_ALL == template.extract_entities(None) - self.assertEqual( - MATCH_ALL, + assert MATCH_ALL == \ template.extract_entities( '{{ closest(states.zone.far_away, ' - 'states.test_domain).entity_id }}')) + 'states.test_domain).entity_id }}') - self.assertEqual( - MATCH_ALL, + assert MATCH_ALL == \ template.extract_entities( - '{{ distance("123", states.test_object_2) }}')) + '{{ distance("123", states.test_object_2) }}') def test_extract_entities_no_match_entities(self): """Test extract entities function with none entities stuff.""" - self.assertEqual( - MATCH_ALL, + assert MATCH_ALL == \ template.extract_entities( - "{{ value_json.tst | timestamp_custom('%Y' True) }}")) + "{{ value_json.tst | timestamp_custom('%Y' True) }}") - self.assertEqual( - MATCH_ALL, + assert MATCH_ALL == \ template.extract_entities(""" {% for state in states.sensor %} {{ state.entity_id }}={{ state.state }},d {% endfor %} - """)) + """) def test_extract_entities_match_entities(self): """Test extract entities function with entities stuff.""" - self.assertListEqual( - ['device_tracker.phone_1'], + assert ['device_tracker.phone_1'] == \ template.extract_entities(""" {% if is_state('device_tracker.phone_1', 'home') %} Ha, Hercules is home! {% else %} Hercules is at {{ states('device_tracker.phone_1') }}. {% endif %} - """)) + """) - self.assertListEqual( - ['binary_sensor.garage_door'], + assert ['binary_sensor.garage_door'] == \ template.extract_entities(""" {{ as_timestamp(states.binary_sensor.garage_door.last_changed) }} - """)) + """) - self.assertListEqual( - ['binary_sensor.garage_door'], + assert ['binary_sensor.garage_door'] == \ template.extract_entities(""" {{ states("binary_sensor.garage_door") }} - """)) + """) - self.assertListEqual( - ['device_tracker.phone_2'], + assert ['device_tracker.phone_2'] == \ template.extract_entities(""" is_state_attr('device_tracker.phone_2', 'battery', 40) - """)) + """) - self.assertListEqual( - sorted([ + assert sorted([ 'device_tracker.phone_1', 'device_tracker.phone_2', - ]), + ]) == \ sorted(template.extract_entities(""" {% if is_state('device_tracker.phone_1', 'home') %} Ha, Hercules is home! {% elif states.device_tracker.phone_2.attributes.battery < 40 %} Hercules you power goes done!. {% endif %} - """))) + """)) - self.assertListEqual( - sorted([ + assert sorted([ 'sensor.pick_humidity', 'sensor.pick_temperature', - ]), + ]) == \ sorted(template.extract_entities(""" {{ states.sensor.pick_temperature.state ~ „°C (“ ~ states.sensor.pick_humidity.state ~ „ %“ }} - """))) + """)) - self.assertListEqual( - sorted([ + assert sorted([ 'sensor.luftfeuchtigkeit_mean', 'input_number.luftfeuchtigkeit', - ]), + ]) == \ sorted(template.extract_entities( "{% if (states('sensor.luftfeuchtigkeit_mean') | int)" " > (states('input_number.luftfeuchtigkeit') | int +1.5)" " %}true{% endif %}" - ))) + )) def test_extract_entities_with_variables(self): """Test extract entities function with variables and entities stuff.""" - self.assertEqual( - ['input_boolean.switch'], + assert ['input_boolean.switch'] == \ template.extract_entities( - "{{ is_state('input_boolean.switch', 'off') }}", {})) + "{{ is_state('input_boolean.switch', 'off') }}", {}) - self.assertEqual( - ['trigger.entity_id'], + assert ['trigger.entity_id'] == \ template.extract_entities( - "{{ is_state(trigger.entity_id, 'off') }}", {})) + "{{ is_state(trigger.entity_id, 'off') }}", {}) - self.assertEqual( - MATCH_ALL, + assert MATCH_ALL == \ template.extract_entities( - "{{ is_state(data, 'off') }}", {})) + "{{ is_state(data, 'off') }}", {}) - self.assertEqual( - ['input_boolean.switch'], + assert ['input_boolean.switch'] == \ template.extract_entities( "{{ is_state(data, 'off') }}", - {'data': 'input_boolean.switch'})) + {'data': 'input_boolean.switch'}) - self.assertEqual( - ['input_boolean.switch'], + assert ['input_boolean.switch'] == \ template.extract_entities( "{{ is_state(trigger.entity_id, 'off') }}", - {'trigger': {'entity_id': 'input_boolean.switch'}})) + {'trigger': {'entity_id': 'input_boolean.switch'}}) - self.assertEqual( - MATCH_ALL, + assert MATCH_ALL == \ template.extract_entities( "{{ is_state('media_player.' ~ where , 'playing') }}", - {'where': 'livingroom'})) + {'where': 'livingroom'}) @asyncio.coroutine diff --git a/tests/test_config.py b/tests/test_config.py index 0e53bc0cd..056bf30ef 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -102,7 +102,7 @@ class TestConfig(unittest.TestCase): """Test if it finds a YAML config file.""" create_file(YAML_PATH) - self.assertEqual(YAML_PATH, config_util.find_config_file(CONFIG_DIR)) + assert YAML_PATH == config_util.find_config_file(CONFIG_DIR) @mock.patch('builtins.print') def test_ensure_config_exists_creates_config(self, mock_print): @@ -112,8 +112,8 @@ class TestConfig(unittest.TestCase): """ config_util.ensure_config_exists(CONFIG_DIR, False) - self.assertTrue(os.path.isfile(YAML_PATH)) - self.assertTrue(mock_print.called) + assert os.path.isfile(YAML_PATH) + assert mock_print.called def test_ensure_config_exists_uses_existing_config(self): """Test that calling ensure_config_exists uses existing config.""" @@ -124,21 +124,20 @@ class TestConfig(unittest.TestCase): content = f.read() # File created with create_file are empty - self.assertEqual('', content) + assert '' == content def test_load_yaml_config_converts_empty_files_to_dict(self): """Test that loading an empty file returns an empty dict.""" create_file(YAML_PATH) - self.assertIsInstance( - config_util.load_yaml_config_file(YAML_PATH), dict) + assert isinstance(config_util.load_yaml_config_file(YAML_PATH), dict) def test_load_yaml_config_raises_error_if_not_dict(self): """Test error raised when YAML file is not a dict.""" with open(YAML_PATH, 'w') as f: f.write('5') - with self.assertRaises(HomeAssistantError): + with pytest.raises(HomeAssistantError): config_util.load_yaml_config_file(YAML_PATH) def test_load_yaml_config_raises_error_if_malformed_yaml(self): @@ -146,7 +145,7 @@ class TestConfig(unittest.TestCase): with open(YAML_PATH, 'w') as f: f.write(':') - with self.assertRaises(HomeAssistantError): + with pytest.raises(HomeAssistantError): config_util.load_yaml_config_file(YAML_PATH) def test_load_yaml_config_raises_error_if_unsafe_yaml(self): @@ -154,7 +153,7 @@ class TestConfig(unittest.TestCase): with open(YAML_PATH, 'w') as f: f.write('hello: !!python/object/apply:os.system') - with self.assertRaises(HomeAssistantError): + with pytest.raises(HomeAssistantError): config_util.load_yaml_config_file(YAML_PATH) def test_load_yaml_config_preserves_key_order(self): @@ -163,9 +162,8 @@ class TestConfig(unittest.TestCase): f.write('hello: 2\n') f.write('world: 1\n') - self.assertEqual( - [('hello', 2), ('world', 1)], - list(config_util.load_yaml_config_file(YAML_PATH).items())) + assert [('hello', 2), ('world', 1)] == \ + list(config_util.load_yaml_config_file(YAML_PATH).items()) @mock.patch('homeassistant.util.location.detect_location_info', return_value=location_util.LocationInfo( @@ -181,7 +179,7 @@ class TestConfig(unittest.TestCase): config = config_util.load_yaml_config_file(YAML_PATH) - self.assertIn(DOMAIN, config) + assert DOMAIN in config ha_conf = config[DOMAIN] @@ -205,10 +203,9 @@ class TestConfig(unittest.TestCase): Non existing folder returns None. """ - self.assertIsNone( - config_util.create_default_config( - os.path.join(CONFIG_DIR, 'non_existing_dir/'), False)) - self.assertTrue(mock_print.called) + assert config_util.create_default_config( + os.path.join(CONFIG_DIR, 'non_existing_dir/'), False) is None + assert mock_print.called # pylint: disable=no-self-use def test_core_config_schema(self): @@ -264,7 +261,7 @@ class TestConfig(unittest.TestCase): """Test that customize_glob preserves order.""" conf = config_util.CORE_CONFIG_SCHEMA( {'customize_glob': OrderedDict()}) - self.assertIsInstance(conf['customize_glob'], OrderedDict) + assert isinstance(conf['customize_glob'], OrderedDict) def _compute_state(self, config): run_coroutine_threadsafe( @@ -306,14 +303,10 @@ class TestConfig(unittest.TestCase): config_util.process_ha_config_upgrade(self.hass) hass_path = self.hass.config.path.return_value - self.assertEqual(mock_os.path.isdir.call_count, 1) - self.assertEqual( - mock_os.path.isdir.call_args, mock.call(hass_path) - ) - self.assertEqual(mock_shutil.rmtree.call_count, 1) - self.assertEqual( - mock_shutil.rmtree.call_args, mock.call(hass_path) - ) + assert mock_os.path.isdir.call_count == 1 + assert mock_os.path.isdir.call_args == mock.call(hass_path) + assert mock_shutil.rmtree.call_count == 1 + assert mock_shutil.rmtree.call_args == mock.call(hass_path) def test_process_config_upgrade(self): """Test update of version on upgrade.""" @@ -327,10 +320,8 @@ class TestConfig(unittest.TestCase): config_util.process_ha_config_upgrade(self.hass) - self.assertEqual(opened_file.write.call_count, 1) - self.assertEqual( - opened_file.write.call_args, mock.call(__version__) - ) + assert opened_file.write.call_count == 1 + assert opened_file.write.call_args == mock.call(__version__) def test_config_upgrade_same_version(self): """Test no update of version on no upgrade.""" @@ -354,9 +345,8 @@ class TestConfig(unittest.TestCase): opened_file = mock_open.return_value # pylint: disable=no-member config_util.process_ha_config_upgrade(self.hass) - self.assertEqual(opened_file.write.call_count, 1) - self.assertEqual( - opened_file.write.call_args, mock.call(__version__)) + assert opened_file.write.call_count == 1 + assert opened_file.write.call_args == mock.call(__version__) @mock.patch('homeassistant.config.shutil') @mock.patch('homeassistant.config.os') diff --git a/tests/test_core.py b/tests/test_core.py index 7ab624447..69cde6c14 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -253,19 +253,17 @@ class TestEvent(unittest.TestCase): for _ in range(2) ] - self.assertEqual(event1, event2) + assert event1 == event2 def test_repr(self): """Test that repr method works.""" - self.assertEqual( - "", - str(ha.Event("TestEvent"))) + assert "" == \ + str(ha.Event("TestEvent")) - self.assertEqual( - "", + assert "" == \ str(ha.Event("TestEvent", {"beer": "nice"}, - ha.EventOrigin.remote))) + ha.EventOrigin.remote)) def test_as_dict(self): """Test as dictionary.""" @@ -284,7 +282,7 @@ class TestEvent(unittest.TestCase): 'user_id': event.context.user_id, }, } - self.assertEqual(expected, event.as_dict()) + assert expected == event.as_dict() class TestEventBus(unittest.TestCase): @@ -310,11 +308,11 @@ class TestEventBus(unittest.TestCase): unsub = self.bus.listen('test', listener) - self.assertEqual(old_count + 1, len(self.bus.listeners)) + assert old_count + 1 == len(self.bus.listeners) # Remove listener unsub() - self.assertEqual(old_count, len(self.bus.listeners)) + assert old_count == len(self.bus.listeners) # Should do nothing now unsub() @@ -357,7 +355,7 @@ class TestEventBus(unittest.TestCase): self.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(runs)) + assert 1 == len(runs) def test_listen_once_event_with_coroutine(self): """Test listen_once_event method.""" @@ -374,7 +372,7 @@ class TestEventBus(unittest.TestCase): self.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(runs)) + assert 1 == len(runs) def test_listen_once_event_with_thread(self): """Test listen_once_event method.""" @@ -390,7 +388,7 @@ class TestEventBus(unittest.TestCase): self.bus.fire('test_event') self.hass.block_till_done() - self.assertEqual(1, len(runs)) + assert 1 == len(runs) def test_thread_event_listener(self): """Test thread event listener.""" @@ -436,59 +434,56 @@ class TestState(unittest.TestCase): def test_init(self): """Test state.init.""" - self.assertRaises( - InvalidEntityFormatError, ha.State, - 'invalid_entity_format', 'test_state') + with pytest.raises(InvalidEntityFormatError): + ha.State('invalid_entity_format', 'test_state') - self.assertRaises( - InvalidStateError, ha.State, - 'domain.long_state', 't' * 256) + with pytest.raises(InvalidStateError): + ha.State('domain.long_state', 't' * 256) def test_domain(self): """Test domain.""" state = ha.State('some_domain.hello', 'world') - self.assertEqual('some_domain', state.domain) + assert 'some_domain' == state.domain def test_object_id(self): """Test object ID.""" state = ha.State('domain.hello', 'world') - self.assertEqual('hello', state.object_id) + assert 'hello' == state.object_id def test_name_if_no_friendly_name_attr(self): """Test if there is no friendly name.""" state = ha.State('domain.hello_world', 'world') - self.assertEqual('hello world', state.name) + assert 'hello world' == state.name def test_name_if_friendly_name_attr(self): """Test if there is a friendly name.""" name = 'Some Unique Name' state = ha.State('domain.hello_world', 'world', {ATTR_FRIENDLY_NAME: name}) - self.assertEqual(name, state.name) + assert name == state.name def test_dict_conversion(self): """Test conversion of dict.""" state = ha.State('domain.hello', 'world', {'some': 'attr'}) - self.assertEqual(state, ha.State.from_dict(state.as_dict())) + assert state == ha.State.from_dict(state.as_dict()) def test_dict_conversion_with_wrong_data(self): """Test conversion with wrong data.""" - self.assertIsNone(ha.State.from_dict(None)) - self.assertIsNone(ha.State.from_dict({'state': 'yes'})) - self.assertIsNone(ha.State.from_dict({'entity_id': 'yes'})) + assert ha.State.from_dict(None) is None + assert ha.State.from_dict({'state': 'yes'}) is None + assert ha.State.from_dict({'entity_id': 'yes'}) is None def test_repr(self): """Test state.repr.""" - self.assertEqual("", - str(ha.State( - "happy.happy", "on", - last_changed=datetime(1984, 12, 8, 12, 0, 0)))) + assert "" == \ + str(ha.State( + "happy.happy", "on", + last_changed=datetime(1984, 12, 8, 12, 0, 0))) - self.assertEqual( - "", + assert "" == \ str(ha.State("happy.happy", "on", {"brightness": 144}, - datetime(1984, 12, 8, 12, 0, 0)))) + datetime(1984, 12, 8, 12, 0, 0))) class TestStateMachine(unittest.TestCase): @@ -509,25 +504,25 @@ class TestStateMachine(unittest.TestCase): def test_is_state(self): """Test is_state method.""" - self.assertTrue(self.states.is_state('light.Bowl', 'on')) - self.assertFalse(self.states.is_state('light.Bowl', 'off')) - self.assertFalse(self.states.is_state('light.Non_existing', 'on')) + assert self.states.is_state('light.Bowl', 'on') + assert not self.states.is_state('light.Bowl', 'off') + assert not self.states.is_state('light.Non_existing', 'on') def test_entity_ids(self): """Test get_entity_ids method.""" ent_ids = self.states.entity_ids() - self.assertEqual(2, len(ent_ids)) - self.assertTrue('light.bowl' in ent_ids) - self.assertTrue('switch.ac' in ent_ids) + assert 2 == len(ent_ids) + assert 'light.bowl' in ent_ids + assert 'switch.ac' in ent_ids ent_ids = self.states.entity_ids('light') - self.assertEqual(1, len(ent_ids)) - self.assertTrue('light.bowl' in ent_ids) + assert 1 == len(ent_ids) + assert 'light.bowl' in ent_ids def test_all(self): """Test everything.""" states = sorted(state.entity_id for state in self.states.all()) - self.assertEqual(['light.bowl', 'switch.ac'], states) + assert ['light.bowl', 'switch.ac'] == states def test_remove(self): """Test remove method.""" @@ -539,21 +534,21 @@ class TestStateMachine(unittest.TestCase): self.hass.bus.listen(EVENT_STATE_CHANGED, callback) - self.assertIn('light.bowl', self.states.entity_ids()) - self.assertTrue(self.states.remove('light.bowl')) + assert 'light.bowl' in self.states.entity_ids() + assert self.states.remove('light.bowl') self.hass.block_till_done() - self.assertNotIn('light.bowl', self.states.entity_ids()) - self.assertEqual(1, len(events)) - self.assertEqual('light.bowl', events[0].data.get('entity_id')) - self.assertIsNotNone(events[0].data.get('old_state')) - self.assertEqual('light.bowl', events[0].data['old_state'].entity_id) - self.assertIsNone(events[0].data.get('new_state')) + assert 'light.bowl' not in self.states.entity_ids() + assert 1 == len(events) + assert 'light.bowl' == events[0].data.get('entity_id') + assert events[0].data.get('old_state') is not None + assert 'light.bowl' == events[0].data['old_state'].entity_id + assert events[0].data.get('new_state') is None # If it does not exist, we should get False - self.assertFalse(self.states.remove('light.Bowl')) + assert not self.states.remove('light.Bowl') self.hass.block_till_done() - self.assertEqual(1, len(events)) + assert 1 == len(events) def test_case_insensitivty(self): """Test insensitivty.""" @@ -568,8 +563,8 @@ class TestStateMachine(unittest.TestCase): self.states.set('light.BOWL', 'off') self.hass.block_till_done() - self.assertTrue(self.states.is_state('light.bowl', 'off')) - self.assertEqual(1, len(runs)) + assert self.states.is_state('light.bowl', 'off') + assert 1 == len(runs) def test_last_changed_not_updated_on_same_state(self): """Test to not update the existing, same state.""" @@ -597,11 +592,11 @@ class TestStateMachine(unittest.TestCase): self.states.set('light.bowl', 'on') self.hass.block_till_done() - self.assertEqual(0, len(events)) + assert 0 == len(events) self.states.set('light.bowl', 'on', None, True) self.hass.block_till_done() - self.assertEqual(1, len(events)) + assert 1 == len(events) def test_service_call_repr(): @@ -647,12 +642,9 @@ class TestServiceRegistry(unittest.TestCase): def test_has_service(self): """Test has_service method.""" - self.assertTrue( - self.services.has_service("tesT_domaiN", "tesT_servicE")) - self.assertFalse( - self.services.has_service("test_domain", "non_existing")) - self.assertFalse( - self.services.has_service("non_existing", "test_service")) + assert self.services.has_service("tesT_domaiN", "tesT_servicE") + assert not self.services.has_service("test_domain", "non_existing") + assert not self.services.has_service("non_existing", "test_service") def test_services(self): """Test services.""" @@ -675,9 +667,9 @@ class TestServiceRegistry(unittest.TestCase): assert self.calls_register[-1].data['domain'] == 'test_domain' assert self.calls_register[-1].data['service'] == 'register_calls' - self.assertTrue( - self.services.call('test_domain', 'REGISTER_CALLS', blocking=True)) - self.assertEqual(1, len(calls)) + assert self.services.call('test_domain', 'REGISTER_CALLS', + blocking=True) + assert 1 == len(calls) def test_call_non_existing_with_blocking(self): """Test non-existing with blocking.""" @@ -706,10 +698,10 @@ class TestServiceRegistry(unittest.TestCase): assert self.calls_register[-1].data['domain'] == 'test_domain' assert self.calls_register[-1].data['service'] == 'register_calls' - self.assertTrue( - self.services.call('test_domain', 'REGISTER_CALLS', blocking=True)) + assert self.services.call('test_domain', 'REGISTER_CALLS', + blocking=True) self.hass.block_till_done() - self.assertEqual(1, len(calls)) + assert 1 == len(calls) def test_callback_service(self): """Test registering and calling an async service.""" @@ -728,10 +720,10 @@ class TestServiceRegistry(unittest.TestCase): assert self.calls_register[-1].data['domain'] == 'test_domain' assert self.calls_register[-1].data['service'] == 'register_calls' - self.assertTrue( - self.services.call('test_domain', 'REGISTER_CALLS', blocking=True)) + assert self.services.call('test_domain', 'REGISTER_CALLS', + blocking=True) self.hass.block_till_done() - self.assertEqual(1, len(calls)) + assert 1 == len(calls) def test_remove_service(self): """Test remove service.""" @@ -778,19 +770,19 @@ class TestConfig(unittest.TestCase): def setUp(self): """Set up things to be run when tests are started.""" self.config = ha.Config() - self.assertIsNone(self.config.config_dir) + assert self.config.config_dir is None def test_path_with_file(self): """Test get_config_path method.""" self.config.config_dir = '/tmp/ha-config' - self.assertEqual("/tmp/ha-config/test.conf", - self.config.path("test.conf")) + assert "/tmp/ha-config/test.conf" == \ + self.config.path("test.conf") def test_path_with_dir_and_file(self): """Test get_config_path method.""" self.config.config_dir = '/tmp/ha-config' - self.assertEqual("/tmp/ha-config/dir/test.conf", - self.config.path("dir", "test.conf")) + assert "/tmp/ha-config/dir/test.conf" == \ + self.config.path("dir", "test.conf") def test_as_dict(self): """Test as dict.""" @@ -808,7 +800,7 @@ class TestConfig(unittest.TestCase): 'version': __version__, } - self.assertEqual(expected, self.config.as_dict()) + assert expected == self.config.as_dict() def test_is_allowed_path(self): """Test is_allowed_path method.""" @@ -843,7 +835,7 @@ class TestConfig(unittest.TestCase): for path in unvalid: assert not self.config.is_allowed_path(path) - with self.assertRaises(AssertionError): + with pytest.raises(AssertionError): self.config.is_allowed_path(None) diff --git a/tests/test_loader.py b/tests/test_loader.py index c4adb9715..90d259c86 100644 --- a/tests/test_loader.py +++ b/tests/test_loader.py @@ -34,8 +34,8 @@ class TestLoader(unittest.TestCase): def test_get_component(self): """Test if get_component works.""" - self.assertEqual(http, loader.get_component(self.hass, 'http')) - self.assertIsNotNone(loader.get_component(self.hass, 'light.hue')) + assert http == loader.get_component(self.hass, 'http') + assert loader.get_component(self.hass, 'light.hue') is not None def test_load_order_component(self): """Test if we can get the proper load order of components.""" @@ -43,23 +43,22 @@ class TestLoader(unittest.TestCase): loader.set_component(self.hass, 'mod2', MockModule('mod2', ['mod1'])) loader.set_component(self.hass, 'mod3', MockModule('mod3', ['mod2'])) - self.assertEqual( - ['mod1', 'mod2', 'mod3'], - loader.load_order_component(self.hass, 'mod3')) + assert ['mod1', 'mod2', 'mod3'] == \ + loader.load_order_component(self.hass, 'mod3') # Create circular dependency loader.set_component(self.hass, 'mod1', MockModule('mod1', ['mod3'])) - self.assertEqual([], loader.load_order_component(self.hass, 'mod3')) + assert [] == loader.load_order_component(self.hass, 'mod3') # Depend on non-existing component loader.set_component(self.hass, 'mod1', MockModule('mod1', ['nonexisting'])) - self.assertEqual([], loader.load_order_component(self.hass, 'mod1')) + assert [] == loader.load_order_component(self.hass, 'mod1') # Try to get load order for non-existing component - self.assertEqual([], loader.load_order_component(self.hass, 'mod1')) + assert [] == loader.load_order_component(self.hass, 'mod1') def test_component_loader(hass): diff --git a/tests/util/test_color.py b/tests/util/test_color.py index 74ba72cd3..b7802d3dc 100644 --- a/tests/util/test_color.py +++ b/tests/util/test_color.py @@ -12,203 +12,203 @@ class TestColorUtil(unittest.TestCase): # pylint: disable=invalid-name def test_color_RGB_to_xy_brightness(self): """Test color_RGB_to_xy_brightness.""" - self.assertEqual((0, 0, 0), - color_util.color_RGB_to_xy_brightness(0, 0, 0)) - self.assertEqual((0.323, 0.329, 255), - color_util.color_RGB_to_xy_brightness(255, 255, 255)) + assert (0, 0, 0) == \ + color_util.color_RGB_to_xy_brightness(0, 0, 0) + assert (0.323, 0.329, 255) == \ + color_util.color_RGB_to_xy_brightness(255, 255, 255) - self.assertEqual((0.136, 0.04, 12), - color_util.color_RGB_to_xy_brightness(0, 0, 255)) + assert (0.136, 0.04, 12) == \ + color_util.color_RGB_to_xy_brightness(0, 0, 255) - self.assertEqual((0.172, 0.747, 170), - color_util.color_RGB_to_xy_brightness(0, 255, 0)) + assert (0.172, 0.747, 170) == \ + color_util.color_RGB_to_xy_brightness(0, 255, 0) - self.assertEqual((0.701, 0.299, 72), - color_util.color_RGB_to_xy_brightness(255, 0, 0)) + assert (0.701, 0.299, 72) == \ + color_util.color_RGB_to_xy_brightness(255, 0, 0) - self.assertEqual((0.701, 0.299, 16), - color_util.color_RGB_to_xy_brightness(128, 0, 0)) + assert (0.701, 0.299, 16) == \ + color_util.color_RGB_to_xy_brightness(128, 0, 0) def test_color_RGB_to_xy(self): """Test color_RGB_to_xy.""" - self.assertEqual((0, 0), - color_util.color_RGB_to_xy(0, 0, 0)) - self.assertEqual((0.323, 0.329), - color_util.color_RGB_to_xy(255, 255, 255)) + assert (0, 0) == \ + color_util.color_RGB_to_xy(0, 0, 0) + assert (0.323, 0.329) == \ + color_util.color_RGB_to_xy(255, 255, 255) - self.assertEqual((0.136, 0.04), - color_util.color_RGB_to_xy(0, 0, 255)) + assert (0.136, 0.04) == \ + color_util.color_RGB_to_xy(0, 0, 255) - self.assertEqual((0.172, 0.747), - color_util.color_RGB_to_xy(0, 255, 0)) + assert (0.172, 0.747) == \ + color_util.color_RGB_to_xy(0, 255, 0) - self.assertEqual((0.701, 0.299), - color_util.color_RGB_to_xy(255, 0, 0)) + assert (0.701, 0.299) == \ + color_util.color_RGB_to_xy(255, 0, 0) - self.assertEqual((0.701, 0.299), - color_util.color_RGB_to_xy(128, 0, 0)) + assert (0.701, 0.299) == \ + color_util.color_RGB_to_xy(128, 0, 0) def test_color_xy_brightness_to_RGB(self): """Test color_xy_brightness_to_RGB.""" - self.assertEqual((0, 0, 0), - color_util.color_xy_brightness_to_RGB(1, 1, 0)) + assert (0, 0, 0) == \ + color_util.color_xy_brightness_to_RGB(1, 1, 0) - self.assertEqual((194, 186, 169), - color_util.color_xy_brightness_to_RGB(.35, .35, 128)) + assert (194, 186, 169) == \ + color_util.color_xy_brightness_to_RGB(.35, .35, 128) - self.assertEqual((255, 243, 222), - color_util.color_xy_brightness_to_RGB(.35, .35, 255)) + assert (255, 243, 222) == \ + color_util.color_xy_brightness_to_RGB(.35, .35, 255) - self.assertEqual((255, 0, 60), - color_util.color_xy_brightness_to_RGB(1, 0, 255)) + assert (255, 0, 60) == \ + color_util.color_xy_brightness_to_RGB(1, 0, 255) - self.assertEqual((0, 255, 0), - color_util.color_xy_brightness_to_RGB(0, 1, 255)) + assert (0, 255, 0) == \ + color_util.color_xy_brightness_to_RGB(0, 1, 255) - self.assertEqual((0, 63, 255), - color_util.color_xy_brightness_to_RGB(0, 0, 255)) + assert (0, 63, 255) == \ + color_util.color_xy_brightness_to_RGB(0, 0, 255) def test_color_xy_to_RGB(self): """Test color_xy_to_RGB.""" - self.assertEqual((255, 243, 222), - color_util.color_xy_to_RGB(.35, .35)) + assert (255, 243, 222) == \ + color_util.color_xy_to_RGB(.35, .35) - self.assertEqual((255, 0, 60), - color_util.color_xy_to_RGB(1, 0)) + assert (255, 0, 60) == \ + color_util.color_xy_to_RGB(1, 0) - self.assertEqual((0, 255, 0), - color_util.color_xy_to_RGB(0, 1)) + assert (0, 255, 0) == \ + color_util.color_xy_to_RGB(0, 1) - self.assertEqual((0, 63, 255), - color_util.color_xy_to_RGB(0, 0)) + assert (0, 63, 255) == \ + color_util.color_xy_to_RGB(0, 0) def test_color_RGB_to_hsv(self): """Test color_RGB_to_hsv.""" - self.assertEqual((0, 0, 0), - color_util.color_RGB_to_hsv(0, 0, 0)) + assert (0, 0, 0) == \ + color_util.color_RGB_to_hsv(0, 0, 0) - self.assertEqual((0, 0, 100), - color_util.color_RGB_to_hsv(255, 255, 255)) + assert (0, 0, 100) == \ + color_util.color_RGB_to_hsv(255, 255, 255) - self.assertEqual((240, 100, 100), - color_util.color_RGB_to_hsv(0, 0, 255)) + assert (240, 100, 100) == \ + color_util.color_RGB_to_hsv(0, 0, 255) - self.assertEqual((120, 100, 100), - color_util.color_RGB_to_hsv(0, 255, 0)) + assert (120, 100, 100) == \ + color_util.color_RGB_to_hsv(0, 255, 0) - self.assertEqual((0, 100, 100), - color_util.color_RGB_to_hsv(255, 0, 0)) + assert (0, 100, 100) == \ + color_util.color_RGB_to_hsv(255, 0, 0) def test_color_hsv_to_RGB(self): """Test color_hsv_to_RGB.""" - self.assertEqual((0, 0, 0), - color_util.color_hsv_to_RGB(0, 0, 0)) + assert (0, 0, 0) == \ + color_util.color_hsv_to_RGB(0, 0, 0) - self.assertEqual((255, 255, 255), - color_util.color_hsv_to_RGB(0, 0, 100)) + assert (255, 255, 255) == \ + color_util.color_hsv_to_RGB(0, 0, 100) - self.assertEqual((0, 0, 255), - color_util.color_hsv_to_RGB(240, 100, 100)) + assert (0, 0, 255) == \ + color_util.color_hsv_to_RGB(240, 100, 100) - self.assertEqual((0, 255, 0), - color_util.color_hsv_to_RGB(120, 100, 100)) + assert (0, 255, 0) == \ + color_util.color_hsv_to_RGB(120, 100, 100) - self.assertEqual((255, 0, 0), - color_util.color_hsv_to_RGB(0, 100, 100)) + assert (255, 0, 0) == \ + color_util.color_hsv_to_RGB(0, 100, 100) def test_color_hsb_to_RGB(self): """Test color_hsb_to_RGB.""" - self.assertEqual((0, 0, 0), - color_util.color_hsb_to_RGB(0, 0, 0)) + assert (0, 0, 0) == \ + color_util.color_hsb_to_RGB(0, 0, 0) - self.assertEqual((255, 255, 255), - color_util.color_hsb_to_RGB(0, 0, 1.0)) + assert (255, 255, 255) == \ + color_util.color_hsb_to_RGB(0, 0, 1.0) - self.assertEqual((0, 0, 255), - color_util.color_hsb_to_RGB(240, 1.0, 1.0)) + assert (0, 0, 255) == \ + color_util.color_hsb_to_RGB(240, 1.0, 1.0) - self.assertEqual((0, 255, 0), - color_util.color_hsb_to_RGB(120, 1.0, 1.0)) + assert (0, 255, 0) == \ + color_util.color_hsb_to_RGB(120, 1.0, 1.0) - self.assertEqual((255, 0, 0), - color_util.color_hsb_to_RGB(0, 1.0, 1.0)) + assert (255, 0, 0) == \ + color_util.color_hsb_to_RGB(0, 1.0, 1.0) def test_color_xy_to_hs(self): """Test color_xy_to_hs.""" - self.assertEqual((47.294, 100), - color_util.color_xy_to_hs(1, 1)) + assert (47.294, 100) == \ + color_util.color_xy_to_hs(1, 1) - self.assertEqual((38.182, 12.941), - color_util.color_xy_to_hs(.35, .35)) + assert (38.182, 12.941) == \ + color_util.color_xy_to_hs(.35, .35) - self.assertEqual((345.882, 100), - color_util.color_xy_to_hs(1, 0)) + assert (345.882, 100) == \ + color_util.color_xy_to_hs(1, 0) - self.assertEqual((120, 100), - color_util.color_xy_to_hs(0, 1)) + assert (120, 100) == \ + color_util.color_xy_to_hs(0, 1) - self.assertEqual((225.176, 100), - color_util.color_xy_to_hs(0, 0)) + assert (225.176, 100) == \ + color_util.color_xy_to_hs(0, 0) def test_color_hs_to_xy(self): """Test color_hs_to_xy.""" - self.assertEqual((0.151, 0.343), - color_util.color_hs_to_xy(180, 100)) + assert (0.151, 0.343) == \ + color_util.color_hs_to_xy(180, 100) - self.assertEqual((0.356, 0.321), - color_util.color_hs_to_xy(350, 12.5)) + assert (0.356, 0.321) == \ + color_util.color_hs_to_xy(350, 12.5) - self.assertEqual((0.229, 0.474), - color_util.color_hs_to_xy(140, 50)) + assert (0.229, 0.474) == \ + color_util.color_hs_to_xy(140, 50) - self.assertEqual((0.474, 0.317), - color_util.color_hs_to_xy(0, 40)) + assert (0.474, 0.317) == \ + color_util.color_hs_to_xy(0, 40) - self.assertEqual((0.323, 0.329), - color_util.color_hs_to_xy(360, 0)) + assert (0.323, 0.329) == \ + color_util.color_hs_to_xy(360, 0) def test_rgb_hex_to_rgb_list(self): """Test rgb_hex_to_rgb_list.""" - self.assertEqual([255, 255, 255], - color_util.rgb_hex_to_rgb_list('ffffff')) + assert [255, 255, 255] == \ + color_util.rgb_hex_to_rgb_list('ffffff') - self.assertEqual([0, 0, 0], - color_util.rgb_hex_to_rgb_list('000000')) + assert [0, 0, 0] == \ + color_util.rgb_hex_to_rgb_list('000000') - self.assertEqual([255, 255, 255, 255], - color_util.rgb_hex_to_rgb_list('ffffffff')) + assert [255, 255, 255, 255] == \ + color_util.rgb_hex_to_rgb_list('ffffffff') - self.assertEqual([0, 0, 0, 0], - color_util.rgb_hex_to_rgb_list('00000000')) + assert [0, 0, 0, 0] == \ + color_util.rgb_hex_to_rgb_list('00000000') - self.assertEqual([51, 153, 255], - color_util.rgb_hex_to_rgb_list('3399ff')) + assert [51, 153, 255] == \ + color_util.rgb_hex_to_rgb_list('3399ff') - self.assertEqual([51, 153, 255, 0], - color_util.rgb_hex_to_rgb_list('3399ff00')) + assert [51, 153, 255, 0] == \ + color_util.rgb_hex_to_rgb_list('3399ff00') def test_color_name_to_rgb_valid_name(self): """Test color_name_to_rgb.""" - self.assertEqual((255, 0, 0), - color_util.color_name_to_rgb('red')) + assert (255, 0, 0) == \ + color_util.color_name_to_rgb('red') - self.assertEqual((0, 0, 255), - color_util.color_name_to_rgb('blue')) + assert (0, 0, 255) == \ + color_util.color_name_to_rgb('blue') - self.assertEqual((0, 128, 0), - color_util.color_name_to_rgb('green')) + assert (0, 128, 0) == \ + color_util.color_name_to_rgb('green') # spaces in the name - self.assertEqual((72, 61, 139), - color_util.color_name_to_rgb('dark slate blue')) + assert (72, 61, 139) == \ + color_util.color_name_to_rgb('dark slate blue') # spaces removed from name - self.assertEqual((72, 61, 139), - color_util.color_name_to_rgb('darkslateblue')) - self.assertEqual((72, 61, 139), - color_util.color_name_to_rgb('dark slateblue')) - self.assertEqual((72, 61, 139), - color_util.color_name_to_rgb('darkslate blue')) + assert (72, 61, 139) == \ + color_util.color_name_to_rgb('darkslateblue') + assert (72, 61, 139) == \ + color_util.color_name_to_rgb('dark slateblue') + assert (72, 61, 139) == \ + color_util.color_name_to_rgb('darkslate blue') def test_color_name_to_rgb_unknown_name_raises_value_error(self): """Test color_name_to_rgb.""" @@ -217,55 +217,55 @@ class TestColorUtil(unittest.TestCase): def test_color_rgb_to_rgbw(self): """Test color_rgb_to_rgbw.""" - self.assertEqual((0, 0, 0, 0), - color_util.color_rgb_to_rgbw(0, 0, 0)) + assert (0, 0, 0, 0) == \ + color_util.color_rgb_to_rgbw(0, 0, 0) - self.assertEqual((0, 0, 0, 255), - color_util.color_rgb_to_rgbw(255, 255, 255)) + assert (0, 0, 0, 255) == \ + color_util.color_rgb_to_rgbw(255, 255, 255) - self.assertEqual((255, 0, 0, 0), - color_util.color_rgb_to_rgbw(255, 0, 0)) + assert (255, 0, 0, 0) == \ + color_util.color_rgb_to_rgbw(255, 0, 0) - self.assertEqual((0, 255, 0, 0), - color_util.color_rgb_to_rgbw(0, 255, 0)) + assert (0, 255, 0, 0) == \ + color_util.color_rgb_to_rgbw(0, 255, 0) - self.assertEqual((0, 0, 255, 0), - color_util.color_rgb_to_rgbw(0, 0, 255)) + assert (0, 0, 255, 0) == \ + color_util.color_rgb_to_rgbw(0, 0, 255) - self.assertEqual((255, 127, 0, 0), - color_util.color_rgb_to_rgbw(255, 127, 0)) + assert (255, 127, 0, 0) == \ + color_util.color_rgb_to_rgbw(255, 127, 0) - self.assertEqual((255, 0, 0, 253), - color_util.color_rgb_to_rgbw(255, 127, 127)) + assert (255, 0, 0, 253) == \ + color_util.color_rgb_to_rgbw(255, 127, 127) - self.assertEqual((0, 0, 0, 127), - color_util.color_rgb_to_rgbw(127, 127, 127)) + assert (0, 0, 0, 127) == \ + color_util.color_rgb_to_rgbw(127, 127, 127) def test_color_rgbw_to_rgb(self): """Test color_rgbw_to_rgb.""" - self.assertEqual((0, 0, 0), - color_util.color_rgbw_to_rgb(0, 0, 0, 0)) + assert (0, 0, 0) == \ + color_util.color_rgbw_to_rgb(0, 0, 0, 0) - self.assertEqual((255, 255, 255), - color_util.color_rgbw_to_rgb(0, 0, 0, 255)) + assert (255, 255, 255) == \ + color_util.color_rgbw_to_rgb(0, 0, 0, 255) - self.assertEqual((255, 0, 0), - color_util.color_rgbw_to_rgb(255, 0, 0, 0)) + assert (255, 0, 0) == \ + color_util.color_rgbw_to_rgb(255, 0, 0, 0) - self.assertEqual((0, 255, 0), - color_util.color_rgbw_to_rgb(0, 255, 0, 0)) + assert (0, 255, 0) == \ + color_util.color_rgbw_to_rgb(0, 255, 0, 0) - self.assertEqual((0, 0, 255), - color_util.color_rgbw_to_rgb(0, 0, 255, 0)) + assert (0, 0, 255) == \ + color_util.color_rgbw_to_rgb(0, 0, 255, 0) - self.assertEqual((255, 127, 0), - color_util.color_rgbw_to_rgb(255, 127, 0, 0)) + assert (255, 127, 0) == \ + color_util.color_rgbw_to_rgb(255, 127, 0, 0) - self.assertEqual((255, 127, 127), - color_util.color_rgbw_to_rgb(255, 0, 0, 253)) + assert (255, 127, 127) == \ + color_util.color_rgbw_to_rgb(255, 0, 0, 253) - self.assertEqual((127, 127, 127), - color_util.color_rgbw_to_rgb(0, 0, 0, 127)) + assert (127, 127, 127) == \ + color_util.color_rgbw_to_rgb(0, 0, 0, 127) def test_color_rgb_to_hex(self): """Test color_rgb_to_hex.""" @@ -281,12 +281,12 @@ class ColorTemperatureMiredToKelvinTests(unittest.TestCase): def test_should_return_25000_kelvin_when_input_is_40_mired(self): """Function should return 25000K if given 40 mired.""" kelvin = color_util.color_temperature_mired_to_kelvin(40) - self.assertEqual(25000, kelvin) + assert 25000 == kelvin def test_should_return_5000_kelvin_when_input_is_200_mired(self): """Function should return 5000K if given 200 mired.""" kelvin = color_util.color_temperature_mired_to_kelvin(200) - self.assertEqual(5000, kelvin) + assert 5000 == kelvin class ColorTemperatureKelvinToMiredTests(unittest.TestCase): @@ -295,12 +295,12 @@ class ColorTemperatureKelvinToMiredTests(unittest.TestCase): def test_should_return_40_mired_when_input_is_25000_kelvin(self): """Function should return 40 mired when given 25000 Kelvin.""" mired = color_util.color_temperature_kelvin_to_mired(25000) - self.assertEqual(40, mired) + assert 40 == mired def test_should_return_200_mired_when_input_is_5000_kelvin(self): """Function should return 200 mired when given 5000 Kelvin.""" mired = color_util.color_temperature_kelvin_to_mired(5000) - self.assertEqual(200, mired) + assert 200 == mired class ColorTemperatureToRGB(unittest.TestCase): @@ -310,13 +310,13 @@ class ColorTemperatureToRGB(unittest.TestCase): """Function should return same value for 999 Kelvin and 0 Kelvin.""" rgb_1 = color_util.color_temperature_to_rgb(999) rgb_2 = color_util.color_temperature_to_rgb(0) - self.assertEqual(rgb_1, rgb_2) + assert rgb_1 == rgb_2 def test_returns_same_value_for_any_two_temperatures_above_40000(self): """Function should return same value for 40001K and 999999K.""" rgb_1 = color_util.color_temperature_to_rgb(40001) rgb_2 = color_util.color_temperature_to_rgb(999999) - self.assertEqual(rgb_1, rgb_2) + assert rgb_1 == rgb_2 def test_should_return_pure_white_at_6600(self): """ @@ -327,19 +327,19 @@ class ColorTemperatureToRGB(unittest.TestCase): guess" approach. """ rgb = color_util.color_temperature_to_rgb(6600) - self.assertEqual((255, 255, 255), rgb) + assert (255, 255, 255) == rgb def test_color_above_6600_should_have_more_blue_than_red_or_green(self): """Function should return a higher blue value for blue-ish light.""" rgb = color_util.color_temperature_to_rgb(6700) - self.assertGreater(rgb[2], rgb[1]) - self.assertGreater(rgb[2], rgb[0]) + assert rgb[2] > rgb[1] + assert rgb[2] > rgb[0] def test_color_below_6600_should_have_more_red_than_blue_or_green(self): """Function should return a higher red value for red-ish light.""" rgb = color_util.color_temperature_to_rgb(6500) - self.assertGreater(rgb[0], rgb[1]) - self.assertGreater(rgb[0], rgb[2]) + assert rgb[0] > rgb[1] + assert rgb[0] > rgb[2] def test_get_color_in_voluptuous(): diff --git a/tests/util/test_distance.py b/tests/util/test_distance.py index 2ad3b42fd..162f1a2fa 100644 --- a/tests/util/test_distance.py +++ b/tests/util/test_distance.py @@ -4,6 +4,7 @@ import unittest import homeassistant.util.distance as distance_util from homeassistant.const import (LENGTH_KILOMETERS, LENGTH_METERS, LENGTH_FEET, LENGTH_MILES) +import pytest INVALID_SYMBOL = 'bob' VALID_SYMBOL = LENGTH_KILOMETERS @@ -14,78 +15,65 @@ class TestDistanceUtil(unittest.TestCase): def test_convert_same_unit(self): """Test conversion from any unit to same unit.""" - self.assertEqual(5, - distance_util.convert(5, LENGTH_KILOMETERS, - LENGTH_KILOMETERS)) - self.assertEqual(2, - distance_util.convert(2, LENGTH_METERS, - LENGTH_METERS)) - self.assertEqual(10, - distance_util.convert(10, LENGTH_MILES, LENGTH_MILES)) - self.assertEqual(9, - distance_util.convert(9, LENGTH_FEET, LENGTH_FEET)) + assert 5 == distance_util.convert(5, LENGTH_KILOMETERS, + LENGTH_KILOMETERS) + assert 2 == distance_util.convert(2, LENGTH_METERS, + LENGTH_METERS) + assert 10 == distance_util.convert(10, LENGTH_MILES, LENGTH_MILES) + assert 9 == distance_util.convert(9, LENGTH_FEET, LENGTH_FEET) def test_convert_invalid_unit(self): """Test exception is thrown for invalid units.""" - with self.assertRaises(ValueError): + with pytest.raises(ValueError): distance_util.convert(5, INVALID_SYMBOL, VALID_SYMBOL) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): distance_util.convert(5, VALID_SYMBOL, INVALID_SYMBOL) def test_convert_nonnumeric_value(self): """Test exception is thrown for nonnumeric type.""" - with self.assertRaises(TypeError): + with pytest.raises(TypeError): distance_util.convert('a', LENGTH_KILOMETERS, LENGTH_METERS) def test_convert_from_miles(self): """Test conversion from miles to other units.""" miles = 5 - self.assertEqual( - distance_util.convert(miles, LENGTH_MILES, LENGTH_KILOMETERS), - 8.04672) - self.assertEqual( - distance_util.convert(miles, LENGTH_MILES, LENGTH_METERS), - 8046.72) - self.assertEqual( - distance_util.convert(miles, LENGTH_MILES, LENGTH_FEET), - 26400.0008448) + assert distance_util.convert( + miles, LENGTH_MILES, LENGTH_KILOMETERS + ) == 8.04672 + assert distance_util.convert(miles, LENGTH_MILES, LENGTH_METERS) == \ + 8046.72 + assert distance_util.convert(miles, LENGTH_MILES, LENGTH_FEET) == \ + 26400.0008448 def test_convert_from_feet(self): """Test conversion from feet to other units.""" feet = 5000 - self.assertEqual( - distance_util.convert(feet, LENGTH_FEET, LENGTH_KILOMETERS), - 1.524) - self.assertEqual( - distance_util.convert(feet, LENGTH_FEET, LENGTH_METERS), - 1524) - self.assertEqual( - distance_util.convert(feet, LENGTH_FEET, LENGTH_MILES), - 0.9469694040000001) + assert distance_util.convert(feet, LENGTH_FEET, LENGTH_KILOMETERS) == \ + 1.524 + assert distance_util.convert(feet, LENGTH_FEET, LENGTH_METERS) == \ + 1524 + assert distance_util.convert(feet, LENGTH_FEET, LENGTH_MILES) == \ + 0.9469694040000001 def test_convert_from_kilometers(self): """Test conversion from kilometers to other units.""" km = 5 - self.assertEqual( - distance_util.convert(km, LENGTH_KILOMETERS, LENGTH_FEET), - 16404.2) - self.assertEqual( - distance_util.convert(km, LENGTH_KILOMETERS, LENGTH_METERS), - 5000) - self.assertEqual( - distance_util.convert(km, LENGTH_KILOMETERS, LENGTH_MILES), - 3.106855) + assert distance_util.convert(km, LENGTH_KILOMETERS, LENGTH_FEET) == \ + 16404.2 + assert distance_util.convert(km, LENGTH_KILOMETERS, LENGTH_METERS) == \ + 5000 + assert distance_util.convert(km, LENGTH_KILOMETERS, LENGTH_MILES) == \ + 3.106855 def test_convert_from_meters(self): """Test conversion from meters to other units.""" m = 5000 - self.assertEqual(distance_util.convert(m, LENGTH_METERS, LENGTH_FEET), - 16404.2) - self.assertEqual( - distance_util.convert(m, LENGTH_METERS, LENGTH_KILOMETERS), - 5) - self.assertEqual(distance_util.convert(m, LENGTH_METERS, LENGTH_MILES), - 3.106855) + assert distance_util.convert(m, LENGTH_METERS, LENGTH_FEET) == \ + 16404.2 + assert distance_util.convert(m, LENGTH_METERS, LENGTH_KILOMETERS) == \ + 5 + assert distance_util.convert(m, LENGTH_METERS, LENGTH_MILES) == \ + 3.106855 diff --git a/tests/util/test_dt.py b/tests/util/test_dt.py index 35a83de6b..52f55fff3 100644 --- a/tests/util/test_dt.py +++ b/tests/util/test_dt.py @@ -3,6 +3,7 @@ import unittest from datetime import datetime, timedelta import homeassistant.util.dt as dt_util +import pytest TEST_TIME_ZONE = 'America/Los_Angeles' @@ -22,14 +23,14 @@ class TestDateUtil(unittest.TestCase): """Test getting a time zone.""" time_zone = dt_util.get_time_zone(TEST_TIME_ZONE) - self.assertIsNotNone(time_zone) - self.assertEqual(TEST_TIME_ZONE, time_zone.zone) + assert time_zone is not None + assert TEST_TIME_ZONE == time_zone.zone def test_get_time_zone_returns_none_for_garbage_time_zone(self): """Test getting a non existing time zone.""" time_zone = dt_util.get_time_zone("Non existing time zone") - self.assertIsNone(time_zone) + assert time_zone is None def test_set_default_time_zone(self): """Test setting default time zone.""" @@ -38,36 +39,34 @@ class TestDateUtil(unittest.TestCase): dt_util.set_default_time_zone(time_zone) # We cannot compare the timezones directly because of DST - self.assertEqual(time_zone.zone, dt_util.now().tzinfo.zone) + assert time_zone.zone == dt_util.now().tzinfo.zone def test_utcnow(self): """Test the UTC now method.""" - self.assertAlmostEqual( - dt_util.utcnow().replace(tzinfo=None), - datetime.utcnow(), - delta=timedelta(seconds=1)) + assert abs(dt_util.utcnow().replace(tzinfo=None)-datetime.utcnow()) < \ + timedelta(seconds=1) def test_now(self): """Test the now method.""" dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE)) - self.assertAlmostEqual( - dt_util.as_utc(dt_util.now()).replace(tzinfo=None), - datetime.utcnow(), - delta=timedelta(seconds=1)) + assert abs( + dt_util.as_utc(dt_util.now()).replace( + tzinfo=None + ) - datetime.utcnow() + ) < timedelta(seconds=1) def test_as_utc_with_naive_object(self): """Test the now method.""" utcnow = datetime.utcnow() - self.assertEqual(utcnow, - dt_util.as_utc(utcnow).replace(tzinfo=None)) + assert utcnow == dt_util.as_utc(utcnow).replace(tzinfo=None) def test_as_utc_with_utc_object(self): """Test UTC time with UTC object.""" utcnow = dt_util.utcnow() - self.assertEqual(utcnow, dt_util.as_utc(utcnow)) + assert utcnow == dt_util.as_utc(utcnow) def test_as_utc_with_local_object(self): """Test the UTC time with local object.""" @@ -75,20 +74,19 @@ class TestDateUtil(unittest.TestCase): localnow = dt_util.now() utcnow = dt_util.as_utc(localnow) - self.assertEqual(localnow, utcnow) - self.assertNotEqual(localnow.tzinfo, utcnow.tzinfo) + assert localnow == utcnow + assert localnow.tzinfo != utcnow.tzinfo def test_as_local_with_naive_object(self): """Test local time with native object.""" now = dt_util.now() - self.assertAlmostEqual( - now, dt_util.as_local(datetime.utcnow()), - delta=timedelta(seconds=1)) + assert abs(now-dt_util.as_local(datetime.utcnow())) < \ + timedelta(seconds=1) def test_as_local_with_local_object(self): """Test local with local object.""" now = dt_util.now() - self.assertEqual(now, now) + assert now == now def test_as_local_with_utc_object(self): """Test local time with UTC object.""" @@ -97,27 +95,26 @@ class TestDateUtil(unittest.TestCase): utcnow = dt_util.utcnow() localnow = dt_util.as_local(utcnow) - self.assertEqual(localnow, utcnow) - self.assertNotEqual(localnow.tzinfo, utcnow.tzinfo) + assert localnow == utcnow + assert localnow.tzinfo != utcnow.tzinfo def test_utc_from_timestamp(self): """Test utc_from_timestamp method.""" - self.assertEqual( - datetime(1986, 7, 9, tzinfo=dt_util.UTC), - dt_util.utc_from_timestamp(521251200)) + assert datetime(1986, 7, 9, tzinfo=dt_util.UTC) == \ + dt_util.utc_from_timestamp(521251200) def test_as_timestamp(self): """Test as_timestamp method.""" ts = 1462401234 utc_dt = dt_util.utc_from_timestamp(ts) - self.assertEqual(ts, dt_util.as_timestamp(utc_dt)) + assert ts == dt_util.as_timestamp(utc_dt) utc_iso = utc_dt.isoformat() - self.assertEqual(ts, dt_util.as_timestamp(utc_iso)) + assert ts == dt_util.as_timestamp(utc_iso) # confirm the ability to handle a string passed in delta = dt_util.as_timestamp("2016-01-01 12:12:12") delta -= dt_util.as_timestamp("2016-01-01 12:12:11") - self.assertEqual(1, delta) + assert 1 == delta def test_parse_datetime_converts_correctly(self): """Test parse_datetime converts strings.""" @@ -131,72 +128,61 @@ class TestDateUtil(unittest.TestCase): def test_parse_datetime_returns_none_for_incorrect_format(self): """Test parse_datetime returns None if incorrect format.""" - self.assertIsNone(dt_util.parse_datetime("not a datetime string")) + assert dt_util.parse_datetime("not a datetime string") is None def test_get_age(self): """Test get_age.""" diff = dt_util.now() - timedelta(seconds=0) - self.assertEqual(dt_util.get_age(diff), "0 seconds") + assert dt_util.get_age(diff) == "0 seconds" diff = dt_util.now() - timedelta(seconds=1) - self.assertEqual(dt_util.get_age(diff), "1 second") + assert dt_util.get_age(diff) == "1 second" diff = dt_util.now() - timedelta(seconds=30) - self.assertEqual(dt_util.get_age(diff), "30 seconds") + assert dt_util.get_age(diff) == "30 seconds" diff = dt_util.now() - timedelta(minutes=5) - self.assertEqual(dt_util.get_age(diff), "5 minutes") + assert dt_util.get_age(diff) == "5 minutes" diff = dt_util.now() - timedelta(minutes=1) - self.assertEqual(dt_util.get_age(diff), "1 minute") + assert dt_util.get_age(diff) == "1 minute" diff = dt_util.now() - timedelta(minutes=300) - self.assertEqual(dt_util.get_age(diff), "5 hours") + assert dt_util.get_age(diff) == "5 hours" diff = dt_util.now() - timedelta(minutes=320) - self.assertEqual(dt_util.get_age(diff), "5 hours") + assert dt_util.get_age(diff) == "5 hours" diff = dt_util.now() - timedelta(minutes=2*60*24) - self.assertEqual(dt_util.get_age(diff), "2 days") + assert dt_util.get_age(diff) == "2 days" diff = dt_util.now() - timedelta(minutes=32*60*24) - self.assertEqual(dt_util.get_age(diff), "1 month") + assert dt_util.get_age(diff) == "1 month" diff = dt_util.now() - timedelta(minutes=365*60*24) - self.assertEqual(dt_util.get_age(diff), "1 year") + assert dt_util.get_age(diff) == "1 year" def test_parse_time_expression(self): """Test parse_time_expression.""" - self.assertEqual( - [x for x in range(60)], + assert [x for x in range(60)] == \ dt_util.parse_time_expression('*', 0, 59) - ) - self.assertEqual( - [x for x in range(60)], + assert [x for x in range(60)] == \ dt_util.parse_time_expression(None, 0, 59) - ) - self.assertEqual( - [x for x in range(0, 60, 5)], + assert [x for x in range(0, 60, 5)] == \ dt_util.parse_time_expression('/5', 0, 59) - ) - self.assertEqual( - [1, 2, 3], + assert [1, 2, 3] == \ dt_util.parse_time_expression([2, 1, 3], 0, 59) - ) - self.assertEqual( - [x for x in range(24)], + assert [x for x in range(24)] == \ dt_util.parse_time_expression('*', 0, 23) - ) - self.assertEqual( - [42], + assert [42] == \ dt_util.parse_time_expression(42, 0, 59) - ) - self.assertRaises(ValueError, dt_util.parse_time_expression, 61, 0, 60) + with pytest.raises(ValueError): + dt_util.parse_time_expression(61, 0, 60) def test_find_next_time_expression_time_basic(self): """Test basic stuff for find_next_time_expression_time.""" @@ -209,25 +195,17 @@ class TestDateUtil(unittest.TestCase): return dt_util.find_next_time_expression_time( dt, seconds, minutes, hours) - self.assertEqual( - datetime(2018, 10, 7, 10, 30, 0), + assert datetime(2018, 10, 7, 10, 30, 0) == \ find(datetime(2018, 10, 7, 10, 20, 0), '*', '/30', 0) - ) - self.assertEqual( - datetime(2018, 10, 7, 10, 30, 0), + assert datetime(2018, 10, 7, 10, 30, 0) == \ find(datetime(2018, 10, 7, 10, 30, 0), '*', '/30', 0) - ) - self.assertEqual( - datetime(2018, 10, 7, 12, 30, 30), + assert datetime(2018, 10, 7, 12, 30, 30) == \ find(datetime(2018, 10, 7, 10, 30, 0), '/3', '/30', [30, 45]) - ) - self.assertEqual( - datetime(2018, 10, 8, 5, 0, 0), + assert datetime(2018, 10, 8, 5, 0, 0) == \ find(datetime(2018, 10, 7, 10, 30, 0), 5, 0, 0) - ) def test_find_next_time_expression_time_dst(self): """Test daylight saving time for find_next_time_expression_time.""" @@ -244,48 +222,32 @@ class TestDateUtil(unittest.TestCase): dt, seconds, minutes, hours) # Entering DST, clocks are rolled forward - self.assertEqual( - tz.localize(datetime(2018, 3, 26, 2, 30, 0)), + assert tz.localize(datetime(2018, 3, 26, 2, 30, 0)) == \ find(tz.localize(datetime(2018, 3, 25, 1, 50, 0)), 2, 30, 0) - ) - self.assertEqual( - tz.localize(datetime(2018, 3, 26, 2, 30, 0)), + assert tz.localize(datetime(2018, 3, 26, 2, 30, 0)) == \ find(tz.localize(datetime(2018, 3, 25, 3, 50, 0)), 2, 30, 0) - ) - self.assertEqual( - tz.localize(datetime(2018, 3, 26, 2, 30, 0)), + assert tz.localize(datetime(2018, 3, 26, 2, 30, 0)) == \ find(tz.localize(datetime(2018, 3, 26, 1, 50, 0)), 2, 30, 0) - ) # Leaving DST, clocks are rolled back - self.assertEqual( - tz.localize(datetime(2018, 10, 28, 2, 30, 0), is_dst=False), + assert tz.localize(datetime(2018, 10, 28, 2, 30, 0), is_dst=False) == \ find(tz.localize(datetime(2018, 10, 28, 2, 5, 0), is_dst=False), 2, 30, 0) - ) - self.assertEqual( - tz.localize(datetime(2018, 10, 28, 2, 30, 0), is_dst=False), + assert tz.localize(datetime(2018, 10, 28, 2, 30, 0), is_dst=False) == \ find(tz.localize(datetime(2018, 10, 28, 2, 55, 0), is_dst=True), 2, 30, 0) - ) - self.assertEqual( - tz.localize(datetime(2018, 10, 28, 4, 30, 0), is_dst=False), + assert tz.localize(datetime(2018, 10, 28, 4, 30, 0), is_dst=False) == \ find(tz.localize(datetime(2018, 10, 28, 2, 55, 0), is_dst=True), 4, 30, 0) - ) - self.assertEqual( - tz.localize(datetime(2018, 10, 28, 2, 30, 0), is_dst=True), + assert tz.localize(datetime(2018, 10, 28, 2, 30, 0), is_dst=True) == \ find(tz.localize(datetime(2018, 10, 28, 2, 5, 0), is_dst=True), 2, 30, 0) - ) - self.assertEqual( - tz.localize(datetime(2018, 10, 29, 2, 30, 0)), + assert tz.localize(datetime(2018, 10, 29, 2, 30, 0)) == \ find(tz.localize(datetime(2018, 10, 28, 2, 55, 0), is_dst=False), 2, 30, 0) - ) diff --git a/tests/util/test_init.py b/tests/util/test_init.py index 1f43c5a4b..10b4fe0ad 100644 --- a/tests/util/test_init.py +++ b/tests/util/test_init.py @@ -5,6 +5,7 @@ from datetime import datetime, timedelta from homeassistant import util import homeassistant.util.dt as dt_util +import pytest class TestUtil(unittest.TestCase): @@ -12,60 +13,56 @@ class TestUtil(unittest.TestCase): def test_sanitize_filename(self): """Test sanitize_filename.""" - self.assertEqual("test", util.sanitize_filename("test")) - self.assertEqual("test", util.sanitize_filename("/test")) - self.assertEqual("test", util.sanitize_filename("..test")) - self.assertEqual("test", util.sanitize_filename("\\test")) - self.assertEqual("test", util.sanitize_filename("\\../test")) + assert "test" == util.sanitize_filename("test") + assert "test" == util.sanitize_filename("/test") + assert "test" == util.sanitize_filename("..test") + assert "test" == util.sanitize_filename("\\test") + assert "test" == util.sanitize_filename("\\../test") def test_sanitize_path(self): """Test sanitize_path.""" - self.assertEqual("test/path", util.sanitize_path("test/path")) - self.assertEqual("test/path", util.sanitize_path("~test/path")) - self.assertEqual("//test/path", - util.sanitize_path("~/../test/path")) + assert "test/path" == util.sanitize_path("test/path") + assert "test/path" == util.sanitize_path("~test/path") + assert "//test/path" == util.sanitize_path("~/../test/path") def test_slugify(self): """Test slugify.""" - self.assertEqual("test", util.slugify("T-!@#$!#@$!$est")) - self.assertEqual("test_more", util.slugify("Test More")) - self.assertEqual("test_more", util.slugify("Test_(More)")) - self.assertEqual("test_more", util.slugify("Tèst_Mörê")) - self.assertEqual("b827eb000000", util.slugify("B8:27:EB:00:00:00")) - self.assertEqual("testcom", util.slugify("test.com")) - self.assertEqual("greg_phone__exp_wayp1", - util.slugify("greg_phone - exp_wayp1")) - self.assertEqual("we_are_we_are_a_test_calendar", - util.slugify("We are, we are, a... Test Calendar")) - self.assertEqual("test_aouss_aou", util.slugify("Tèst_äöüß_ÄÖÜ")) + assert "test" == util.slugify("T-!@#$!#@$!$est") + assert "test_more" == util.slugify("Test More") + assert "test_more" == util.slugify("Test_(More)") + assert "test_more" == util.slugify("Tèst_Mörê") + assert "b827eb000000" == util.slugify("B8:27:EB:00:00:00") + assert "testcom" == util.slugify("test.com") + assert "greg_phone__exp_wayp1" == \ + util.slugify("greg_phone - exp_wayp1") + assert "we_are_we_are_a_test_calendar" == \ + util.slugify("We are, we are, a... Test Calendar") + assert "test_aouss_aou" == util.slugify("Tèst_äöüß_ÄÖÜ") def test_repr_helper(self): """Test repr_helper.""" - self.assertEqual("A", util.repr_helper("A")) - self.assertEqual("5", util.repr_helper(5)) - self.assertEqual("True", util.repr_helper(True)) - self.assertEqual("test=1", - util.repr_helper({"test": 1})) - self.assertEqual("1986-07-09T12:00:00+00:00", - util.repr_helper(datetime(1986, 7, 9, 12, 0, 0))) + assert "A" == util.repr_helper("A") + assert "5" == util.repr_helper(5) + assert "True" == util.repr_helper(True) + assert "test=1" == util.repr_helper({"test": 1}) + assert "1986-07-09T12:00:00+00:00" == \ + util.repr_helper(datetime(1986, 7, 9, 12, 0, 0)) def test_convert(self): """Test convert.""" - self.assertEqual(5, util.convert("5", int)) - self.assertEqual(5.0, util.convert("5", float)) - self.assertEqual(True, util.convert("True", bool)) - self.assertEqual(1, util.convert("NOT A NUMBER", int, 1)) - self.assertEqual(1, util.convert(None, int, 1)) - self.assertEqual(1, util.convert(object, int, 1)) + assert 5 == util.convert("5", int) + assert 5.0 == util.convert("5", float) + assert util.convert("True", bool) is True + assert 1 == util.convert("NOT A NUMBER", int, 1) + assert 1 == util.convert(None, int, 1) + assert 1 == util.convert(object, int, 1) def test_ensure_unique_string(self): """Test ensure_unique_string.""" - self.assertEqual( - "Beer_3", - util.ensure_unique_string("Beer", ["Beer", "Beer_2"])) - self.assertEqual( - "Beer", - util.ensure_unique_string("Beer", ["Wine", "Soda"])) + assert "Beer_3" == \ + util.ensure_unique_string("Beer", ["Beer", "Beer_2"]) + assert "Beer" == \ + util.ensure_unique_string("Beer", ["Wine", "Soda"]) def test_ordered_enum(self): """Test the ordered enum class.""" @@ -76,96 +73,96 @@ class TestUtil(unittest.TestCase): SECOND = 2 THIRD = 3 - self.assertTrue(TestEnum.SECOND >= TestEnum.FIRST) - self.assertTrue(TestEnum.SECOND >= TestEnum.SECOND) - self.assertFalse(TestEnum.SECOND >= TestEnum.THIRD) + assert TestEnum.SECOND >= TestEnum.FIRST + assert TestEnum.SECOND >= TestEnum.SECOND + assert not (TestEnum.SECOND >= TestEnum.THIRD) - self.assertTrue(TestEnum.SECOND > TestEnum.FIRST) - self.assertFalse(TestEnum.SECOND > TestEnum.SECOND) - self.assertFalse(TestEnum.SECOND > TestEnum.THIRD) + assert TestEnum.SECOND > TestEnum.FIRST + assert not (TestEnum.SECOND > TestEnum.SECOND) + assert not (TestEnum.SECOND > TestEnum.THIRD) - self.assertFalse(TestEnum.SECOND <= TestEnum.FIRST) - self.assertTrue(TestEnum.SECOND <= TestEnum.SECOND) - self.assertTrue(TestEnum.SECOND <= TestEnum.THIRD) + assert not (TestEnum.SECOND <= TestEnum.FIRST) + assert TestEnum.SECOND <= TestEnum.SECOND + assert TestEnum.SECOND <= TestEnum.THIRD - self.assertFalse(TestEnum.SECOND < TestEnum.FIRST) - self.assertFalse(TestEnum.SECOND < TestEnum.SECOND) - self.assertTrue(TestEnum.SECOND < TestEnum.THIRD) + assert not (TestEnum.SECOND < TestEnum.FIRST) + assert not (TestEnum.SECOND < TestEnum.SECOND) + assert TestEnum.SECOND < TestEnum.THIRD # Python will raise a TypeError if the <, <=, >, >= methods # raise a NotImplemented error. - self.assertRaises(TypeError, - lambda x, y: x < y, TestEnum.FIRST, 1) + with pytest.raises(TypeError): + TestEnum.FIRST < 1 - self.assertRaises(TypeError, - lambda x, y: x <= y, TestEnum.FIRST, 1) + with pytest.raises(TypeError): + TestEnum.FIRST <= 1 - self.assertRaises(TypeError, - lambda x, y: x > y, TestEnum.FIRST, 1) + with pytest.raises(TypeError): + TestEnum.FIRST > 1 - self.assertRaises(TypeError, - lambda x, y: x >= y, TestEnum.FIRST, 1) + with pytest.raises(TypeError): + TestEnum.FIRST >= 1 def test_ordered_set(self): """Test ordering of set.""" set1 = util.OrderedSet([1, 2, 3, 4]) set2 = util.OrderedSet([3, 4, 5]) - self.assertEqual(4, len(set1)) - self.assertEqual(3, len(set2)) + assert 4 == len(set1) + assert 3 == len(set2) - self.assertIn(1, set1) - self.assertIn(2, set1) - self.assertIn(3, set1) - self.assertIn(4, set1) - self.assertNotIn(5, set1) + assert 1 in set1 + assert 2 in set1 + assert 3 in set1 + assert 4 in set1 + assert 5 not in set1 - self.assertNotIn(1, set2) - self.assertNotIn(2, set2) - self.assertIn(3, set2) - self.assertIn(4, set2) - self.assertIn(5, set2) + assert 1 not in set2 + assert 2 not in set2 + assert 3 in set2 + assert 4 in set2 + assert 5 in set2 set1.add(5) - self.assertIn(5, set1) + assert 5 in set1 set1.discard(5) - self.assertNotIn(5, set1) + assert 5 not in set1 # Try again while key is not in set1.discard(5) - self.assertNotIn(5, set1) + assert 5 not in set1 - self.assertEqual([1, 2, 3, 4], list(set1)) - self.assertEqual([4, 3, 2, 1], list(reversed(set1))) + assert [1, 2, 3, 4] == list(set1) + assert [4, 3, 2, 1] == list(reversed(set1)) - self.assertEqual(1, set1.pop(False)) - self.assertEqual([2, 3, 4], list(set1)) + assert 1 == set1.pop(False) + assert [2, 3, 4] == list(set1) - self.assertEqual(4, set1.pop()) - self.assertEqual([2, 3], list(set1)) + assert 4 == set1.pop() + assert [2, 3] == list(set1) - self.assertEqual('OrderedSet()', str(util.OrderedSet())) - self.assertEqual('OrderedSet([2, 3])', str(set1)) + assert 'OrderedSet()' == str(util.OrderedSet()) + assert 'OrderedSet([2, 3])' == str(set1) - self.assertEqual(set1, util.OrderedSet([2, 3])) - self.assertNotEqual(set1, util.OrderedSet([3, 2])) - self.assertEqual(set1, set([2, 3])) - self.assertEqual(set1, {3, 2}) - self.assertEqual(set1, [2, 3]) - self.assertEqual(set1, [3, 2]) - self.assertNotEqual(set1, {2}) + assert set1 == util.OrderedSet([2, 3]) + assert set1 != util.OrderedSet([3, 2]) + assert set1 == set([2, 3]) + assert set1 == {3, 2} + assert set1 == [2, 3] + assert set1 == [3, 2] + assert set1 != {2} set3 = util.OrderedSet(set1) set3.update(set2) - self.assertEqual([3, 4, 5, 2], set3) - self.assertEqual([3, 4, 5, 2], set1 | set2) - self.assertEqual([3], set1 & set2) - self.assertEqual([2], set1 - set2) + assert [3, 4, 5, 2] == set3 + assert [3, 4, 5, 2] == set1 | set2 + assert [3] == set1 & set2 + assert [2] == set1 - set2 set1.update([1, 2], [5, 6]) - self.assertEqual([2, 3, 1, 5, 6], set1) + assert [2, 3, 1, 5, 6] == set1 def test_throttle(self): """Test the add cooldown decorator.""" @@ -188,36 +185,36 @@ class TestUtil(unittest.TestCase): test_throttle1() test_throttle2() - self.assertEqual(1, len(calls1)) - self.assertEqual(1, len(calls2)) + assert 1 == len(calls1) + assert 1 == len(calls2) # Call second time. Methods should not get called test_throttle1() test_throttle2() - self.assertEqual(1, len(calls1)) - self.assertEqual(1, len(calls2)) + assert 1 == len(calls1) + assert 1 == len(calls2) # Call again, overriding throttle, only first one should fire test_throttle1(no_throttle=True) test_throttle2(no_throttle=True) - self.assertEqual(2, len(calls1)) - self.assertEqual(1, len(calls2)) + assert 2 == len(calls1) + assert 1 == len(calls2) with patch('homeassistant.util.utcnow', return_value=plus3): test_throttle1() test_throttle2() - self.assertEqual(2, len(calls1)) - self.assertEqual(1, len(calls2)) + assert 2 == len(calls1) + assert 1 == len(calls2) with patch('homeassistant.util.utcnow', return_value=plus5): test_throttle1() test_throttle2() - self.assertEqual(3, len(calls1)) - self.assertEqual(2, len(calls2)) + assert 3 == len(calls1) + assert 2 == len(calls2) def test_throttle_per_instance(self): """Test that the throttle method is done per instance of a class.""" @@ -229,8 +226,8 @@ class TestUtil(unittest.TestCase): """Test the throttle.""" return True - self.assertTrue(Tester().hello()) - self.assertTrue(Tester().hello()) + assert Tester().hello() + assert Tester().hello() def test_throttle_on_method(self): """Test that throttle works when wrapping a method.""" @@ -244,8 +241,8 @@ class TestUtil(unittest.TestCase): tester = Tester() throttled = util.Throttle(timedelta(seconds=1))(tester.hello) - self.assertTrue(throttled()) - self.assertIsNone(throttled()) + assert throttled() + assert throttled() is None def test_throttle_on_two_method(self): """Test that throttle works when wrapping two methods.""" @@ -264,8 +261,8 @@ class TestUtil(unittest.TestCase): tester = Tester() - self.assertTrue(tester.hello()) - self.assertTrue(tester.goodbye()) + assert tester.hello() + assert tester.goodbye() @patch.object(util, 'random') def test_get_random_string(self, mock_random): diff --git a/tests/util/test_json.py b/tests/util/test_json.py index 53f62682b..414a9f400 100644 --- a/tests/util/test_json.py +++ b/tests/util/test_json.py @@ -7,6 +7,7 @@ from tempfile import mkdtemp from homeassistant.util.json import (SerializationError, load_json, save_json) from homeassistant.exceptions import HomeAssistantError +import pytest # Test data that can be saved as JSON TEST_JSON_A = {"a": 1, "B": "two"} @@ -38,7 +39,7 @@ class TestJSON(unittest.TestCase): fname = self._path_for("test1") save_json(fname, TEST_JSON_A) data = load_json(fname) - self.assertEqual(data, TEST_JSON_A) + assert data == TEST_JSON_A # Skipped on Windows @unittest.skipIf(sys.platform.startswith('win'), @@ -48,9 +49,9 @@ class TestJSON(unittest.TestCase): fname = self._path_for("test2") save_json(fname, TEST_JSON_A, private=True) data = load_json(fname) - self.assertEqual(data, TEST_JSON_A) + assert data == TEST_JSON_A stats = os.stat(fname) - self.assertEqual(stats.st_mode & 0o77, 0) + assert stats.st_mode & 0o77 == 0 def test_overwrite_and_reload(self): """Test that we can overwrite an existing file and read back.""" @@ -58,12 +59,12 @@ class TestJSON(unittest.TestCase): save_json(fname, TEST_JSON_A) save_json(fname, TEST_JSON_B) data = load_json(fname) - self.assertEqual(data, TEST_JSON_B) + assert data == TEST_JSON_B def test_save_bad_data(self): """Test error from trying to save unserialisable data.""" fname = self._path_for("test4") - with self.assertRaises(SerializationError): + with pytest.raises(SerializationError): save_json(fname, TEST_BAD_OBJECT) def test_load_bad_data(self): @@ -71,5 +72,5 @@ class TestJSON(unittest.TestCase): fname = self._path_for("test5") with open(fname, "w") as fh: fh.write(TEST_BAD_SERIALIED) - with self.assertRaises(HomeAssistantError): + with pytest.raises(HomeAssistantError): load_json(fname) diff --git a/tests/util/test_unit_system.py b/tests/util/test_unit_system.py index 83edb0561..31b2d49b4 100644 --- a/tests/util/test_unit_system.py +++ b/tests/util/test_unit_system.py @@ -17,6 +17,7 @@ from homeassistant.const import ( TEMPERATURE, VOLUME ) +import pytest SYSTEM_NAME = 'TEST' INVALID_UNIT = 'INVALID' @@ -27,27 +28,27 @@ class TestUnitSystem(unittest.TestCase): def test_invalid_units(self): """Test errors are raised when invalid units are passed in.""" - with self.assertRaises(ValueError): + with pytest.raises(ValueError): UnitSystem(SYSTEM_NAME, INVALID_UNIT, LENGTH_METERS, VOLUME_LITERS, MASS_GRAMS) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): UnitSystem(SYSTEM_NAME, TEMP_CELSIUS, INVALID_UNIT, VOLUME_LITERS, MASS_GRAMS) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): UnitSystem(SYSTEM_NAME, TEMP_CELSIUS, LENGTH_METERS, INVALID_UNIT, MASS_GRAMS) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): UnitSystem(SYSTEM_NAME, TEMP_CELSIUS, LENGTH_METERS, VOLUME_LITERS, INVALID_UNIT) def test_invalid_value(self): """Test no conversion happens if value is non-numeric.""" - with self.assertRaises(TypeError): + with pytest.raises(TypeError): METRIC_SYSTEM.length('25a', LENGTH_KILOMETERS) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): METRIC_SYSTEM.temperature('50K', TEMP_CELSIUS) def test_as_dict(self): @@ -59,75 +60,62 @@ class TestUnitSystem(unittest.TestCase): MASS: MASS_GRAMS } - self.assertEqual(expected, METRIC_SYSTEM.as_dict()) + assert expected == METRIC_SYSTEM.as_dict() def test_temperature_same_unit(self): """Test no conversion happens if to unit is same as from unit.""" - self.assertEqual( - 5, + assert 5 == \ METRIC_SYSTEM.temperature(5, - METRIC_SYSTEM.temperature_unit)) + METRIC_SYSTEM.temperature_unit) def test_temperature_unknown_unit(self): """Test no conversion happens if unknown unit.""" - with self.assertRaises(ValueError): + with pytest.raises(ValueError): METRIC_SYSTEM.temperature(5, 'K') def test_temperature_to_metric(self): """Test temperature conversion to metric system.""" - self.assertEqual( - 25, - METRIC_SYSTEM.temperature(25, METRIC_SYSTEM.temperature_unit)) - self.assertEqual( - 26.7, + assert 25 == \ + METRIC_SYSTEM.temperature(25, METRIC_SYSTEM.temperature_unit) + assert 26.7 == \ round(METRIC_SYSTEM.temperature( - 80, IMPERIAL_SYSTEM.temperature_unit), 1)) + 80, IMPERIAL_SYSTEM.temperature_unit), 1) def test_temperature_to_imperial(self): """Test temperature conversion to imperial system.""" - self.assertEqual( - 77, - IMPERIAL_SYSTEM.temperature(77, IMPERIAL_SYSTEM.temperature_unit)) - self.assertEqual( - 77, - IMPERIAL_SYSTEM.temperature(25, METRIC_SYSTEM.temperature_unit)) + assert 77 == \ + IMPERIAL_SYSTEM.temperature(77, IMPERIAL_SYSTEM.temperature_unit) + assert 77 == \ + IMPERIAL_SYSTEM.temperature(25, METRIC_SYSTEM.temperature_unit) def test_length_unknown_unit(self): """Test length conversion with unknown from unit.""" - with self.assertRaises(ValueError): + with pytest.raises(ValueError): METRIC_SYSTEM.length(5, 'fr') def test_length_to_metric(self): """Test length conversion to metric system.""" - self.assertEqual( - 100, + assert 100 == \ METRIC_SYSTEM.length(100, METRIC_SYSTEM.length_unit) - ) - self.assertEqual( - 8.04672, + assert 8.04672 == \ METRIC_SYSTEM.length(5, IMPERIAL_SYSTEM.length_unit) - ) def test_length_to_imperial(self): """Test length conversion to imperial system.""" - self.assertEqual( - 100, + assert 100 == \ IMPERIAL_SYSTEM.length(100, IMPERIAL_SYSTEM.length_unit) - ) - self.assertEqual( - 3.106855, + assert 3.106855 == \ IMPERIAL_SYSTEM.length(5, METRIC_SYSTEM.length_unit) - ) def test_properties(self): """Test the unit properties are returned as expected.""" - self.assertEqual(LENGTH_KILOMETERS, METRIC_SYSTEM.length_unit) - self.assertEqual(TEMP_CELSIUS, METRIC_SYSTEM.temperature_unit) - self.assertEqual(MASS_GRAMS, METRIC_SYSTEM.mass_unit) - self.assertEqual(VOLUME_LITERS, METRIC_SYSTEM.volume_unit) + assert LENGTH_KILOMETERS == METRIC_SYSTEM.length_unit + assert TEMP_CELSIUS == METRIC_SYSTEM.temperature_unit + assert MASS_GRAMS == METRIC_SYSTEM.mass_unit + assert VOLUME_LITERS == METRIC_SYSTEM.volume_unit def test_is_metric(self): """Test the is metric flag.""" - self.assertTrue(METRIC_SYSTEM.is_metric) - self.assertFalse(IMPERIAL_SYSTEM.is_metric) + assert METRIC_SYSTEM.is_metric + assert not IMPERIAL_SYSTEM.is_metric diff --git a/tests/util/test_volume.py b/tests/util/test_volume.py index e78e099d7..26208d37b 100644 --- a/tests/util/test_volume.py +++ b/tests/util/test_volume.py @@ -4,6 +4,7 @@ import unittest import homeassistant.util.volume as volume_util from homeassistant.const import (VOLUME_LITERS, VOLUME_MILLILITERS, VOLUME_GALLONS, VOLUME_FLUID_OUNCE) +import pytest INVALID_SYMBOL = 'bob' VALID_SYMBOL = VOLUME_LITERS @@ -14,36 +15,35 @@ class TestVolumeUtil(unittest.TestCase): def test_convert_same_unit(self): """Test conversion from any unit to same unit.""" - self.assertEqual(2, volume_util.convert(2, VOLUME_LITERS, - VOLUME_LITERS)) - self.assertEqual(3, volume_util.convert(3, VOLUME_MILLILITERS, - VOLUME_MILLILITERS)) - self.assertEqual(4, volume_util.convert(4, VOLUME_GALLONS, - VOLUME_GALLONS)) - self.assertEqual(5, volume_util.convert(5, VOLUME_FLUID_OUNCE, - VOLUME_FLUID_OUNCE)) + assert 2 == volume_util.convert(2, VOLUME_LITERS, VOLUME_LITERS) + assert 3 == volume_util.convert(3, VOLUME_MILLILITERS, + VOLUME_MILLILITERS) + assert 4 == volume_util.convert(4, VOLUME_GALLONS, + VOLUME_GALLONS) + assert 5 == volume_util.convert(5, VOLUME_FLUID_OUNCE, + VOLUME_FLUID_OUNCE) def test_convert_invalid_unit(self): """Test exception is thrown for invalid units.""" - with self.assertRaises(ValueError): + with pytest.raises(ValueError): volume_util.convert(5, INVALID_SYMBOL, VALID_SYMBOL) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): volume_util.convert(5, VALID_SYMBOL, INVALID_SYMBOL) def test_convert_nonnumeric_value(self): """Test exception is thrown for nonnumeric type.""" - with self.assertRaises(TypeError): + with pytest.raises(TypeError): volume_util.convert('a', VOLUME_GALLONS, VOLUME_LITERS) def test_convert_from_liters(self): """Test conversion from liters to other units.""" liters = 5 - self.assertEqual(volume_util.convert(liters, VOLUME_LITERS, - VOLUME_GALLONS), 1.321) + assert volume_util.convert(liters, VOLUME_LITERS, + VOLUME_GALLONS) == 1.321 def test_convert_from_gallons(self): """Test conversion from gallons to other units.""" gallons = 5 - self.assertEqual(volume_util.convert(gallons, VOLUME_GALLONS, - VOLUME_LITERS), 18.925) + assert volume_util.convert(gallons, VOLUME_GALLONS, + VOLUME_LITERS) == 18.925 diff --git a/tests/util/test_yaml.py b/tests/util/test_yaml.py index d08915b34..2eab75cb9 100644 --- a/tests/util/test_yaml.py +++ b/tests/util/test_yaml.py @@ -43,14 +43,14 @@ class TestYaml(unittest.TestCase): def test_unhashable_key(self): """Test an unhasable key.""" files = {YAML_CONFIG_FILE: 'message:\n {{ states.state }}'} - with self.assertRaises(HomeAssistantError), \ + with pytest.raises(HomeAssistantError), \ patch_yaml_files(files): load_yaml_config_file(YAML_CONFIG_FILE) def test_no_key(self): """Test item without a key.""" files = {YAML_CONFIG_FILE: 'a: a\nnokeyhere'} - with self.assertRaises(HomeAssistantError), \ + with pytest.raises(HomeAssistantError), \ patch_yaml_files(files): yaml.load_yaml(YAML_CONFIG_FILE) @@ -73,7 +73,7 @@ class TestYaml(unittest.TestCase): def test_invalid_environment_variable(self): """Test config file with no environment variable sat.""" conf = "password: !env_var PASSWORD" - with self.assertRaises(HomeAssistantError): + with pytest.raises(HomeAssistantError): with io.StringIO(conf) as file: yaml.yaml.safe_load(file) @@ -261,7 +261,8 @@ class TestYaml(unittest.TestCase): def test_load_yaml_encoding_error(self, mock_open): """Test raising a UnicodeDecodeError.""" mock_open.side_effect = UnicodeDecodeError('', b'', 1, 0, '') - self.assertRaises(HomeAssistantError, yaml.load_yaml, 'test') + with pytest.raises(HomeAssistantError): + yaml.load_yaml('test') def test_dump(self): """The that the dump method returns empty None values.""" @@ -332,12 +333,12 @@ class TestSecrets(unittest.TestCase): def test_secrets_from_yaml(self): """Did secrets load ok.""" expected = {'api_password': 'pwhttp'} - self.assertEqual(expected, self._yaml['http']) + assert expected == self._yaml['http'] expected = { 'username': 'un1', 'password': 'pw1'} - self.assertEqual(expected, self._yaml['component']) + assert expected == self._yaml['component'] def test_secrets_from_parent_folder(self): """Test loading secrets from parent foler.""" @@ -350,7 +351,7 @@ class TestSecrets(unittest.TestCase): ' password: !secret comp1_pw\n' '') - self.assertEqual(expected, self._yaml['http']) + assert expected == self._yaml['http'] def test_secret_overrides_parent(self): """Test loading current directory secret overrides the parent.""" @@ -365,13 +366,13 @@ class TestSecrets(unittest.TestCase): ' password: !secret comp1_pw\n' '') - self.assertEqual(expected, self._yaml['http']) + assert expected == self._yaml['http'] def test_secrets_from_unrelated_fails(self): """Test loading secrets from unrelated folder fails.""" load_yaml(os.path.join(self._unrelated_path, yaml.SECRET_YAML), 'test: failure') - with self.assertRaises(HomeAssistantError): + with pytest.raises(HomeAssistantError): load_yaml(os.path.join(self._sub_folder_path, 'sub.yaml'), 'http:\n' ' api_password: !secret test') @@ -380,12 +381,12 @@ class TestSecrets(unittest.TestCase): """Test keyring fallback & get_password.""" yaml.keyring = None # Ensure its not there yaml_str = 'http:\n api_password: !secret http_pw_keyring' - with self.assertRaises(yaml.HomeAssistantError): + with pytest.raises(yaml.HomeAssistantError): load_yaml(self._yaml_path, yaml_str) yaml.keyring = FakeKeyring({'http_pw_keyring': 'yeah'}) _yaml = load_yaml(self._yaml_path, yaml_str) - self.assertEqual({'http': {'api_password': 'yeah'}}, _yaml) + assert {'http': {'api_password': 'yeah'}} == _yaml @patch.object(yaml, 'credstash') def test_secrets_credstash(self, mock_credstash): @@ -395,11 +396,11 @@ class TestSecrets(unittest.TestCase): _yaml = load_yaml(self._yaml_path, yaml_str) log = logging.getLogger() log.error(_yaml['http']) - self.assertEqual({'api_password': 'yeah'}, _yaml['http']) + assert {'api_password': 'yeah'} == _yaml['http'] def test_secrets_logger_removed(self): """Ensure logger: debug was removed.""" - with self.assertRaises(yaml.HomeAssistantError): + with pytest.raises(yaml.HomeAssistantError): load_yaml(self._yaml_path, 'api_password: !secret logger') @patch('homeassistant.util.yaml._LOGGER.error') @@ -418,7 +419,7 @@ class TestSecrets(unittest.TestCase): ' comp1_un: un1\n' ' comp1_pw: pw1\n') yaml.clear_secret_cache() - with self.assertRaises(HomeAssistantError): + with pytest.raises(HomeAssistantError): load_yaml(self._yaml_path, 'http:\n' ' api_password: !secret http_pw\n'