def test_raise_communication_error_on_empty(self, mock): """Test failure on empty response""" query_url = 'https://api.carson.live/api/v1.4.3/me/' mock.get(query_url, status_code=500) token, _ = get_encoded_token() auth = CarsonAuth(USERNAME, PASSWORD, token) with self.assertRaises(CarsonCommunicationError): auth.authenticated_query(query_url) self.assertTrue(mock.called)
def setUp(self): """Setup unit test and load mock.""" with requests_mock.Mocker() as mock: # Setup URL Mocking self.token, _ = get_encoded_token() self._init_default_mocks(mock, 'carson_me.json') self.carson = Carson(USERNAME, PASSWORD, self.token) self.first_building = self.carson.first_building self.user = self.carson.first_building self.first_camera = next(iter(self.first_building.cameras)) self.first_door = next(iter(self.first_building.doors))
def test_raise_communication_error_wrong_json(self, mock): """Test failure on response with missing keys""" query_url = 'https://api.carson.live/api/v1.4.3/me/' mock.get(query_url, text=load_fixture('carson.live', 'carson_missing_keys.json')) token, _ = get_encoded_token() auth = CarsonAuth(USERNAME, PASSWORD, token) with self.assertRaises(CarsonCommunicationError): auth.authenticated_query(query_url) self.assertTrue(mock.called)
def test_auth_valid_token_init(self): """Test default class initialization with token""" token, token_payload = get_encoded_token() mock_token_update_cb = Mock() auth = CarsonAuth(USERNAME, PASSWORD, token, mock_token_update_cb) self.assertEqual(auth.username, USERNAME) self.assertEqual(auth.token, token) self.assertEqual(auth.token_payload, token_payload) self.assertEqual(auth.token_expiration_date, token_payload.get('exp')) self.assertTrue(auth.valid_token()) # make sure that token update cb is not executed with an initial token. mock_token_update_cb.assert_not_called()
def test_successful_query_with_initial_token(self, mock): """Test query with initial valid token""" query_url = 'https://api.carson.live/api/v1.4.3/me/' mock.get(query_url, text=load_fixture('carson.live', 'carson_me.json')) token, _ = get_encoded_token() auth = CarsonAuth(USERNAME, PASSWORD, token) auth.authenticated_query(query_url) # Token unchanged self.assertEqual(token, auth.token) self.assertEqual(1, mock.call_count) self.assertEqual('JWT {}'.format(token), mock.last_request.headers.get('Authorization'))
def test_expired_token_is_invalid(self): """Test expired token validation""" token, _ = get_encoded_token(-60) auth = CarsonAuth(USERNAME, PASSWORD, token) self.assertFalse(auth.valid_token())