def testReadHttpResponse_Expected404(self):
        conn = mock.Mock()
        conn.req_params = {'uri': 'uri', 'method': 'method'}
        conn.request.return_value = (mock.Mock(status=404),
                                     b'content\xe2\x9c\x94')

        content = gerrit_util.ReadHttpResponse(conn, (404, ))
        self.assertEqual('', content.getvalue())
    def testReadHttpResponse_ClientError(self):
        conn = mock.Mock(req_params={'uri': 'uri', 'method': 'method'})
        conn.request.return_value = (mock.Mock(status=404), b'')

        with self.assertRaises(gerrit_util.GerritError) as cm:
            gerrit_util.ReadHttpResponse(conn)

        self.assertEqual(404, cm.exception.http_status)
    def testReadHttpResponse_200(self):
        conn = mock.Mock()
        conn.req_params = {'uri': 'uri', 'method': 'method'}
        conn.request.return_value = (mock.Mock(status=200),
                                     b'content\xe2\x9c\x94')

        content = gerrit_util.ReadHttpResponse(conn)
        self.assertEqual('content✔', content.getvalue())
        metrics.collector.add_repeated.assert_called_once_with(
            'http_requests', 'http_metrics')
    def testReadHttpResponse_ServerErrorAndSuccess(self):
        conn = mock.Mock(req_params={'uri': 'uri', 'method': 'method'})
        conn.request.side_effect = [
            (mock.Mock(status=500), b''),
            (mock.Mock(status=200), b'content\xe2\x9c\x94'),
        ]

        self.assertEqual('content✔',
                         gerrit_util.ReadHttpResponse(conn).getvalue())
        self.assertEqual(2, len(conn.request.mock_calls))
        gerrit_util.time_sleep.assert_called_once_with(1.5)
    def testReadHttpResponse_ServerError(self):
        conn = mock.Mock(req_params={'uri': 'uri', 'method': 'method'})
        conn.request.return_value = (mock.Mock(status=500), b'')

        with self.assertRaises(gerrit_util.GerritError) as cm:
            gerrit_util.ReadHttpResponse(conn)

        self.assertEqual(500, cm.exception.http_status)
        self.assertEqual(gerrit_util.TRY_LIMIT, len(conn.request.mock_calls))
        self.assertEqual([mock.call(1.5), mock.call(3)],
                         gerrit_util.time_sleep.mock_calls)
    def testReadHttpResponse_AuthenticationIssue(self):
        for status in (302, 401, 403):
            response = mock.Mock(status=status)
            response.get.return_value = None
            conn = mock.Mock(req_params={'uri': 'uri', 'method': 'method'})
            conn.request.return_value = (response, b'')

            with mock.patch('sys.stdout', StringIO()):
                with self.assertRaises(gerrit_util.GerritError) as cm:
                    gerrit_util.ReadHttpResponse(conn)

                self.assertEqual(status, cm.exception.http_status)
                self.assertIn('Your Gerrit credentials might be misconfigured',
                              sys.stdout.getvalue())
Exemple #7
0
    def test_get_git_version_unrecognized(self, mockPopen):
        """Tests that we can get the git version."""
        mockProcess = mock.Mock()
        mockProcess.communicate.side_effect = [('Blah blah blah', 'blah blah')]
        mockPopen.side_effect = [mockProcess]

        self.assertIsNone(metrics_utils.get_git_version())
Exemple #8
0
    def test_get_git_version(self, mockPopen):
        """Tests that we can get the git version."""
        mockProcess = mock.Mock()
        mockProcess.communicate.side_effect = [('git version 2.18.0.123.foo',
                                                '')]
        mockPopen.side_effect = [mockProcess]

        self.assertEqual('2.18.0', metrics_utils.get_git_version())
Exemple #9
0
 def _mock_local_auth(self, account_id, secret, rpc_port):
   self.mock(auth, '_load_luci_context', mock.Mock())
   auth._load_luci_context.return_value = {
     'local_auth': {
       'default_account_id': account_id,
       'secret': secret,
       'rpc_port': rpc_port,
     }
   }
Exemple #10
0
  def setUp(self):
    self.config_file = os.path.join(ROOT_DIR, 'metrics.cfg')
    self.collector = metrics.MetricsCollector()

    # Keep track of the URL requests, file reads/writes and subprocess spawned.
    self.urllib2 = mock.Mock()
    self.print_notice = mock.Mock()
    self.Popen = mock.Mock()
    self.FileWrite = mock.Mock()
    self.FileRead = mock.Mock()

    mock.patch('metrics.urllib2', self.urllib2).start()
    mock.patch('metrics.subprocess.Popen', self.Popen).start()
    mock.patch('metrics.gclient_utils.FileWrite', self.FileWrite).start()
    mock.patch('metrics.gclient_utils.FileRead', self.FileRead).start()
    mock.patch('metrics.metrics_utils.print_notice', self.print_notice).start()

    # Patch the methods used to get the system information, so we have a known
    # environment.
    mock.patch('metrics.tempfile.mkstemp',
               lambda: (None, '/tmp/metrics.json')).start()
    mock.patch('metrics.time.time',
               TimeMock()).start()
    mock.patch('metrics.metrics_utils.get_python_version',
               lambda: '2.7.13').start()
    mock.patch('metrics.gclient_utils.GetMacWinOrLinux',
               lambda: 'linux').start()
    mock.patch('metrics.detect_host_arch.HostArch',
               lambda: 'x86').start()
    mock.patch('metrics_utils.get_repo_timestamp',
               lambda _: 1234).start()

    self.default_metrics = {
        "python_version": "2.7.13",
        "execution_time": 1000,
        "timestamp": 0,
        "exit_code": 0,
        "command": "fun",
        "depot_tools_age": 1234,
        "host_arch": "x86",
        "host_os": "linux",
    }

    self.addCleanup(mock.patch.stopall)
Exemple #11
0
    def test_disables_metrics_if_cant_write_config(self):
        self.FileRead.side_effect = [IOError(2, 'No such file or directory')]
        mock_response = mock.Mock()
        self.urllib2.urlopen.side_effect = [mock_response]
        mock_response.getcode.side_effect = [200]
        self.FileWrite.side_effect = [IOError(13, 'Permission denied.')]

        self.assertTrue(self.collector.config.is_googler)
        self.assertFalse(self.collector.config.opted_in)
        self.assertEqual(self.collector.config.countdown, 10)
Exemple #12
0
 def _mock_local_auth(self, account_id, secret, rpc_port):
   self.mock(os, 'environ', {'LUCI_CONTEXT': 'default/test/path'})
   self.mock(auth, '_load_luci_context', mock.Mock())
   auth._load_luci_context.return_value = {
     'local_auth': {
       'default_account_id': account_id,
       'secret': secret,
       'rpc_port': rpc_port,
     }
   }
  def test_writes_config_if_not_exists(self):
    self.FileRead.side_effect = [IOError(2, "No such file or directory")]
    mock_response = mock.Mock()
    self.urllib2.urlopen.side_effect = [mock_response]
    mock_response.getcode.side_effect = [200]

    self.assertTrue(self.collector.config.is_googler)
    self.assertIsNone(self.collector.config.opted_in)
    self.assertEqual(self.collector.config.countdown, 10)

    self.assert_writes_file(
        self.config_file,
        {'is-googler': True, 'countdown': 10, 'opt-in': None, 'version': 0})
 def setUp(self):
     super(CheckCallAndFilterTestCase, self).setUp()
     self.printfn = io.StringIO()
     self.stdout = io.BytesIO()
     if sys.version_info.major == 2:
         mock.patch('sys.stdout', self.stdout).start()
         mock.patch('__builtin__.print', self.printfn.write).start()
     else:
         mock.patch('sys.stdout', mock.Mock()).start()
         mock.patch('sys.stdout.buffer', self.stdout).start()
         mock.patch('builtins.print', self.printfn.write).start()
     mock.patch('sys.stdout.flush', lambda: None).start()
     self.addCleanup(mock.patch.stopall)
Exemple #15
0
    def testAuthorize(self):
        http = mock.Mock()
        http_request = http.request
        http_request.__name__ = '__name__'

        authenticator = auth.Authenticator()
        authenticator._access_token = auth.AccessToken('token', None)

        authorized = authenticator.authorize(http)
        authorized.request('https://example.com',
                           method='POST',
                           body='body',
                           headers={'header': 'value'})
        http_request.assert_called_once_with(
            'https://example.com', 'POST', 'body', {
                'header': 'value',
                'Authorization': 'Bearer token'
            }, mock.ANY, mock.ANY)
def _mockResponse(status, content):
  mock_response = (mock.Mock(status=status), content)
  mock.patch('auth.httplib2.Http.request', return_value=mock_response).start()
Exemple #17
0
 def _mock_loc_server_resp(self, status, content):
   mock_resp = mock.Mock()
   mock_resp.status = status
   self.mock(httplib2.Http, 'request', mock.Mock())
   httplib2.Http.request.return_value = (mock_resp, content)