• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""Tests for sso_discovery."""
2
3import mock
4import unittest
5import subprocess
6
7from skylab_venv import sso_discovery
8
9
10class SsoDiscoveryTest(unittest.TestCase):
11  """Test sso_discovery."""
12
13  URL = 'https://TEST_URL.com'
14
15  def setUp(self):
16    super(SsoDiscoveryTest, self).setUp()
17    patcher = mock.patch.object(subprocess, 'check_output')
18    self.mock_run_cmd = patcher.start()
19    self.addCleanup(patcher.stop)
20
21  def testSsoRequestWhenFailToRunSsoClientCmd(self):
22    """Test sso_request when fail to run the sso_client command."""
23    self.mock_run_cmd.side_effect = subprocess.CalledProcessError(
24        returncode=1, cmd='test_cmd')
25
26    with self.assertRaises(sso_discovery.BadHttpRequestException):
27       sso_discovery.sso_request(self.URL)
28
29  def testSsoRequestWithAcceptEncodingHeader(self):
30    """Test sso_request when accept-encoding header is given."""
31    self.mock_run_cmd.return_value = '''HTTP/1.1 200 OK
32content-type: application/json
33\r\n\r\n
34{"test": "test"}'''
35
36    sso_discovery.sso_request(self.URL, headers={'accept-encoding': 'test'})
37
38    self.mock_run_cmd.assert_called_with(
39        ['sso_client', '--url', self.URL, '-dump_header'])
40
41  def testSsoRequestWhenFailToParseStatusFromHttpResponse(self):
42    """Test sso_request when fail to parse status from the http response."""
43    self.mock_run_cmd.return_value = 'invalid response'
44    with self.assertRaises(sso_discovery.BadHttpResponseException) as e:
45      sso_discovery.sso_request(self.URL)
46
47  def testSsoRequestWhenNoBodyContentInHttpResponse(self):
48    """Test sso_request when body is missing from the http response."""
49    http_response = '''HTTP/1.1 404 Not Found
50fake_header: fake_value'''
51
52    self.mock_run_cmd.return_value = http_response
53    resp, body = sso_discovery.sso_request(self.URL)
54
55    self.mock_run_cmd.assert_called_with(
56        ['sso_client', '--url', self.URL, '-dump_header'])
57    self.assertEqual(resp.status, 404)
58    self.assertEqual(resp['body'], '')
59    self.assertEqual(resp['headers'], http_response)
60    self.assertEqual(body, '')
61
62  def testSsoRequestWithSuccessfulHttpResponse(self):
63    """Test sso_request with 200 http response."""
64    http_response = '''HTTP/1.1 200 OK
65content-type: application/json
66\r\n\r\n
67{"test": "test"}'''
68
69    self.mock_run_cmd.return_value = http_response
70    resp, body = sso_discovery.sso_request(self.URL)
71
72    self.mock_run_cmd.assert_called_with(
73        ['sso_client', '--url', self.URL, '-dump_header'])
74    self.assertEqual(resp.status, 200)
75    self.assertEqual(resp['body'], '{"test": "test"}')
76    self.assertEqual(resp['headers'],
77                     'HTTP/1.1 200 OK\ncontent-type: application/json')
78    self.assertEqual(body, '{"test": "test"}')
79
80
81if __name__ == '__main__':
82  unittest.main()
83